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
// SPDX-FileCopyrightText: Copyright 2025 Au-Zone Technologies
// SPDX-License-Identifier: Apache-2.0
use edgefirst_decoder::{DetectBox, ProtoData, ProtoLayout, Segmentation};
use edgefirst_tensor::{
PixelFormat, PixelLayout, Tensor, TensorMapTrait, TensorMemory, TensorTrait,
};
use std::collections::BTreeSet;
use std::ffi::{c_char, c_void, CStr};
use std::time::Instant;
use super::cache::CachedImport;
use super::EglDisplayKind;
use super::cache::{BufferImportKey, CacheKind, GlCacheStats, ImportCache};
use super::platform::{GlPlatform, Platform};
/// The platform display/context owned by this processor — `GlContext` on
/// Linux, `AngleDisplay` (per-processor ANGLE context) on macOS.
type PlatformDisplay = <Platform as GlPlatform>::Display;
/// The owned platform import the caches hold (`EglImage` / `IoSurfacePbuffer`).
type PlatformImport = <Platform as GlPlatform>::Import;
/// The `Copy` import handle (`egl::Image` / `egl::Surface`).
type PlatformHandle = <Platform as GlPlatform>::ImportHandle;
use super::resources::{Buffer, FrameBuffer, GlProgram, Texture};
use super::shaders::{
check_gl_error, generate_color_shader, generate_instanced_segmentation_shader,
generate_nv_to_rgba_int8_shader_2d, generate_nv_to_rgba_shader_2d,
generate_packed_f32_nhwc_shader, generate_packed_rgba8_int8_shader_2d,
generate_packed_rgba8_shader_2d, generate_planar_rgb_f16_packed_shader,
generate_planar_rgb_int8_shader, generate_planar_rgb_int8_shader_2d,
generate_planar_rgb_shader, generate_planar_rgb_shader_2d, generate_proto_dequant_shader_int8,
generate_proto_repack_compute_shader, generate_proto_segmentation_shader,
generate_proto_segmentation_shader_f32, generate_proto_segmentation_shader_int8_bilinear,
generate_proto_segmentation_shader_int8_nearest, generate_segmentation_shader,
generate_texture_fragment_shader, generate_texture_fragment_shader_yuv,
generate_texture_int8_shader, generate_texture_int8_shader_yuv, generate_vertex_shader,
};
use super::{Int8InterpolationMode, RegionOfInterest, TransferBackend};
use crate::{Crop, Error, Flip, ImageProcessorTrait, ResolvedCrop, Rotation, DEFAULT_COLORS};
use edgefirst_tensor::TensorDyn;
/// Linux GL float (F16/F32) preprocessing paths. Declared as a child of
/// `processor` so its `impl GLProcessorST` block can reach this module's
/// private fields (the float programs, EGLImage caches, capability flags, …)
/// without promoting them to `pub(super)`.
mod float;
// Re-export the float classifier/support items at the `processor` module path
// so the dispatch in `convert()` and the `gl::tests` unit tests keep using
// `processor::{...}` paths unchanged.
pub(super) use float::{classify_float_render, float_render_support, FloatRenderPath};
// `dma_f16_packed_layout` is only reached through this re-export by the
// `gl::tests` unit tests (via `processor::dma_f16_packed_layout`); the lib body
// itself does not reference it, so the unused-import lint can't see the use.
#[allow(unused_imports)]
pub(super) use float::dma_f16_packed_layout;
/// Which GPU/CPU path was taken for the most recent NV* convert call.
///
/// Recorded by `draw_nv_texture_2d` / `draw_camera_texture_eglimage` / CPU
/// fallback so that tests and the profiler can assert that DMA NV* inputs never
/// silently fall back to CPU. Only meaningful immediately after a convert whose
/// source is `Nv12`/`Nv16`/`Nv24`; it is not reset for non-NV* converts (a
/// reader observing it after, say, an RGBA convert sees the prior NV* value).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum NvConvertPath {
/// Driver-decoded YUV via `samplerExternalOES` EGLImage. The GPU driver
/// performs YUV→RGB (matrix + chroma upsampling); colorimetry is only as
/// correct as the driver's EGL hint support. Required for true-multiplane
/// NV12 (separate Y/UV fds). Was "Path A".
ExternalSampler,
/// R8 `texelFetch` shader applying the exact per-tensor YUV→RGB matrix in
/// the shader (ES 3.0, no extension). Portable and identical across GPUs;
/// no width constraint (uses the 64-aligned stride). Was "Path B".
ShaderR8,
/// CPU fallback (EGLImage creation failed or format not DMA-backed).
Cpu,
/// Not yet set (initial state, or non-NV* convert).
None,
}
/// Client preference for the NV* GPU conversion path, set via
/// `EDGEFIRST_NV_CONVERT_PATH` (`sampler` | `shader` | `auto`).
///
/// `Auto` prefers [`NvConvertPath::ShaderR8`] (portable, colorimetry-exact)
/// wherever possible, using [`NvConvertPath::ExternalSampler`] only when the
/// shader path is impossible (true-multiplane NV12). The forced variants are
/// for benchmarking and platform bring-up; an impossible force logs a warning
/// and falls back rather than failing.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum NvPathPref {
Auto,
ForceSampler,
ForceShader,
}
/// Bound destination render target for one convert, produced by
/// [`GLProcessorST::bind_dst`]. The GL counterpart of
/// [`super::render::DstLowering`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum DstTarget {
/// The destination buffer itself is the FBO colour attachment (EGLImage
/// renderbuffer or texture): the render writes it directly, no readback.
ZeroCopyImage,
/// Offscreen texture render target; `readback` copies the result out.
Texture { readback: DstReadback },
}
/// How a [`DstTarget::Texture`] render reaches the destination tensor.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum DstReadback {
/// `glReadPixels` straight into the mapped Mem tensor.
Mem,
/// `glReadPixels` into this destination PBO's PACK binding.
Pbo(u32),
}
impl DstReadback {
/// The PBO id in the `Option` shape `readback_rendered` consumes.
fn pbo_id(self) -> Option<u32> {
match self {
DstReadback::Mem => None,
DstReadback::Pbo(id) => Some(id),
}
}
}
/// Borrowed proto data for the layered-float render plans: the
/// dispatcher's dtype arm keeps the `TensorMap` alive and hands the typed
/// view down to `render_proto_layers`, which matches it against
/// `ProtoPlan::upload`.
enum ProtoLayersData<'a> {
F32(ndarray::ArrayView3<'a, f32>),
F16(ndarray::ArrayView3<'a, half::f16>),
}
/// Uniform locations for one `nv_r8` program variant, resolved once at link
/// time — `glGetUniformLocation` is a per-call string lookup in the driver
/// and the NV draw previously issued 12 per frame.
#[derive(Clone, Copy)]
struct NvUniformLocs {
img_size: i32,
tex_width: i32,
chroma_shift: i32,
chroma_lines: i32,
y_offset: i32,
y_scale: i32,
c_vr: i32,
c_ug: i32,
c_vg: i32,
c_ub: i32,
}
/// Uniform locations for one float-path program, resolved once per program
/// — previously up to five `GetUniformLocation` string lookups per float
/// draw (`draw_float_quad`). Same pattern as [`NvUniformLocs`]. A location
/// of `-1` (uniform absent in that program variant) is harmless: GL ignores
/// `Uniform*` calls with location `-1` by specification.
#[derive(Clone, Copy)]
pub(super) struct FloatQuadLocs {
pub(super) sampler: i32,
pub(super) src_rect_uv: i32,
pub(super) dst_rect_px: i32,
pub(super) pad_color: i32,
pub(super) dst_image_size: i32,
}
/// Per-program uniform state for one `nv_r8` variant. Uniform values are
/// per-program GL state and persist across draws, so the constant sampler
/// binding (`src` = unit 0) is uploaded once at resolve time and
/// `last_colorimetry` lets the draw skip re-uploading the six YUV-matrix
/// floats while the source's (encoding, range) is unchanged.
struct NvUniformState {
locs: NvUniformLocs,
last_colorimetry: Option<(
edgefirst_tensor::ColorEncoding,
edgefirst_tensor::ColorRange,
)>,
}
impl NvUniformState {
fn resolve(program: &GlProgram) -> Self {
unsafe {
edgefirst_gl::gl::UseProgram(program.id);
let loc = |name: &std::ffi::CStr| {
edgefirst_gl::gl::GetUniformLocation(program.id, name.as_ptr())
};
// Constant: the NV shaders always sample `src` from unit 0.
edgefirst_gl::gl::Uniform1i(loc(c"src"), 0);
NvUniformState {
locs: NvUniformLocs {
img_size: loc(c"img_size"),
tex_width: loc(c"tex_width"),
chroma_shift: loc(c"chroma_shift"),
chroma_lines: loc(c"chroma_lines"),
y_offset: loc(c"y_offset"),
y_scale: loc(c"y_scale"),
c_vr: loc(c"c_vr"),
c_ug: loc(c"c_ug"),
c_vg: loc(c"c_vg"),
c_ub: loc(c"c_ub"),
},
last_colorimetry: None,
}
}
}
}
/// OpenGL single-threaded image converter.
pub struct GLProcessorST {
camera_eglimage_texture: Texture,
camera_normal_texture: Texture,
render_texture: Texture,
segmentation_texture: Texture,
segmentation_program: GlProgram,
instanced_segmentation_program: GlProgram,
proto_texture: Texture,
proto_segmentation_program: GlProgram,
proto_segmentation_int8_nearest_program: GlProgram,
proto_segmentation_int8_bilinear_program: GlProgram,
proto_dequant_int8_program: GlProgram,
proto_segmentation_f32_program: GlProgram,
color_program: GlProgram,
/// Last opacity value set on shader uniforms (avoids redundant GL calls).
cached_opacity: f32,
/// Allocated proto texture dimensions for SubImage3D fast path: (w, h, layers, internal_fmt).
proto_tex_dims: (usize, usize, usize, u32),
/// Whether GL_OES_texture_float_linear is available (allows GL_LINEAR on R32F textures).
has_float_linear: bool,
/// Whether GL_EXT_texture_format_BGRA8888 is available (allows BGRA destinations).
pub(super) has_bgra: bool,
/// Whether `GL_EXT_color_buffer_float` is advertised in the
/// extension string, i.e. the GPU can render to an F32 color
/// attachment. The probe is extension-string only — GLES 3.2 core
/// also mandates F32 color buffers, but this flag does not consult
/// `GL_VERSION`, so a 3.2-core context without the extension string
/// reports `false`. Surfaced through `RenderDtypeSupport`; on Linux
/// this gates the F32 NHWC PBO render path
/// (`FloatRenderPath::PboF32Nhwc`) via `classify_float_render`.
pub(super) supports_f32_color: bool,
/// Whether `GL_EXT_color_buffer_half_float` is advertised, i.e. the
/// GPU can render to an F16 color attachment. Surfaced through
/// `RenderDtypeSupport`; on Linux this gates the F16 NCHW PBO and
/// zero-copy DMA-BUF render paths (`FloatRenderPath::PboF16Nchw`,
/// `FloatRenderPath::ZeroCopyF16Nchw`) via `classify_float_render`.
pub(super) supports_f16_color: bool,
/// Interpolation mode for int8 proto textures.
int8_interpolation_mode: Int8InterpolationMode,
/// Intermediate FBO texture for two-pass int8 dequant path.
proto_dequant_texture: Texture,
/// Allocated dequant texture dims for the recreate-on-change gate:
/// (w, h, layers, internal_fmt). Mirrors `proto_tex_dims`.
proto_dequant_tex_dims: (usize, usize, usize, u32),
/// Persistent FBO for the two-pass int8 dequant render — previously a
/// fresh `FrameBuffer::new()` per call.
proto_dequant_fbo: FrameBuffer,
/// Per-detection quad uniform locations, `(program_id, mask_coeff,
/// class_index)`, re-resolved only when the bound proto program
/// changes. `Cell` because the resolving call sites hold `&self`
/// borrows of the program; id 0 = unresolved.
proto_quad_locs: std::cell::Cell<(u32, i32, i32)>,
/// Compute shader program for HWC→CHW proto repack (GLES 3.1 only).
proto_repack_compute_program: Option<u32>,
/// `(width, height, num_protos)` uniform locations for the compute
/// program, resolved once at compile — previously three
/// GetUniformLocation string lookups per dispatch.
proto_compute_locs: (i32, i32, i32),
/// SSBO for proto data upload (compute shader path).
proto_ssbo: u32,
/// Current allocated size of proto SSBO in bytes (0 = not allocated).
proto_ssbo_size: usize,
vertex_buffer: Buffer,
texture_buffer: Buffer,
/// Persistent FBO for the convert() render path.
/// Created once, reused by re-attaching textures each frame.
convert_fbo: FrameBuffer,
/// Persistent FBO for draw_decoded_masks / draw_proto_masks render path.
/// Separate from convert_fbo so EGLImage binding state is not shared
/// between convert and draw, avoiding redundant EGLImageTargetTexture2DOES
/// calls on every frame when both paths are used.
draw_fbo: FrameBuffer,
/// Texture used as FBO color attachment for draw operations (DMA path).
/// Separate from render_texture so EGLImageTargetTexture2DOES calls made
/// by convert do not invalidate the draw path's bound EGLImage, and
/// vice versa.
draw_render_texture: Texture,
/// EGLImage cache for source DMA buffers.
src_egl_cache: ImportCache<PlatformImport>,
/// EGLImage cache for destination DMA buffers.
dst_egl_cache: ImportCache<PlatformImport>,
/// Whether the BGRA byte-swap workaround warning has been logged.
bgra_warned: bool,
/// Reusable RGBA staging buffer for `read_pixels_into`'s fallback path
/// (drivers whose implementation read-pair rejects direct RGB/RED
/// reads — ANGLE/Metal, V3D). Grown on demand, kept at high-water mark.
readback_scratch: Vec<u8>,
/// Whether the GPU is a Verisilicon/Vivante core (detected via GL_RENDERER).
/// Used to block operations known to cause unrecoverable GPU hangs.
pub(super) is_vivante: bool,
/// Whether the GPU is a virtualized/paravirtual device (GL_RENDERER).
/// Concurrent GL across contexts mis-renders on paravirtual Metal
/// (observed on macOS CI runners: parallel processors produce ~60-86%
/// diverged output bytes); such devices get the Full serialization
/// policy, like Vivante.
is_virtual_gpu: bool,
/// Whether to use renderbuffer-backed EGLImages for DMA destinations.
///
/// Set `EDGEFIRST_OPENGL_RENDERSURFACE=1` to enable (required on i.MX 95 / Mali-G310
/// with Neutron NPU DMA-BUF destinations). Defaults to `false` (texture path) for
/// 0.13.x compatibility with Vivante (i.MX 8MP). Will become the automatic default
/// on non-Vivante platforms in a future release after broader testing.
use_renderbuffer: bool,
/// Intermediate RGBA texture for two-pass packed RGB conversion.
/// Pass 1 renders YUYV/NV12→RGBA here; Pass 2 packs RGBA→RGB to DMA dest.
packed_rgb_intermediate_tex: Texture,
/// FBO for pass 1 of packed RGB conversion (renders to intermediate texture).
packed_rgb_fbo: FrameBuffer,
/// Current allocated size of the intermediate texture (0,0 = unallocated).
packed_rgb_intermediate_size: (usize, usize),
texture_program: GlProgram,
/// External-OES sampler programs (`None` where the platform lacks
/// `GL_OES_EGL_image_external_essl3` — ANGLE/Metal).
texture_program_yuv: Option<GlProgram>,
/// Int8 variant of texture_program — applies XOR 0x80 bias in fragment shader.
texture_int8_program: GlProgram,
/// Int8 variant of texture_program_yuv — applies XOR 0x80 bias in fragment shader.
texture_int8_program_yuv: Option<GlProgram>,
texture_program_planar: Option<GlProgram>,
/// Shader: existing planar RGB with int8 bias (XOR 0x80) applied to output.
texture_program_planar_int8: Option<GlProgram>,
/// YUYV (RG-sampled) → RGBA, portable `sampler2D` — the zero-copy
/// IOSurface source path on macOS (and a future heap-YUYV upload).
yuyv_program_2d: GlProgram,
/// Link-time uniform locations for `yuyv_program_2d`
/// (src_size, y_offset, y_scale, c_vr, c_ug, c_vg, c_ub).
yuyv_2d_locs: [i32; 7],
/// Shader: packed RGB -> RGBA8 packing (2D texture source, pass 2).
packed_rgba8_program_2d: GlProgram,
/// Shader: packed RGB int8 -> RGBA8 packing with XOR 0x80 (2D texture source, pass 2).
packed_rgba8_int8_program_2d: GlProgram,
/// Shader: planar RGB from 2D texture (two-pass NV12→RGBA→PlanarRgb workaround).
texture_program_planar_2d: GlProgram,
/// Shader: planar RGB int8 from 2D texture (two-pass NV12→RGBA→PlanarRgb workaround).
texture_program_planar_int8_2d: GlProgram,
/// Shader: RGBA8 → R32F-wide F32 NHWC `[H,W,3]` packed render (PBO float path).
float_f32_nhwc_program: GlProgram,
/// Shader: RGBA8 → RGBA16F-packed F16 NCHW `[3,H,W]` render (PBO float path).
float_f16_nchw_program: GlProgram,
/// Float render target texture (R32F or RGBA16F), reattached to `convert_fbo`.
float_render_texture: Texture,
/// Cached storage spec of `float_render_texture`: `(packed_w, packed_h,
/// internal_format)`. Mirrors the `proto_tex_dims` pattern: only call
/// `TexImage2D` (storage spec) when this changes; otherwise reuse the
/// existing storage (skip the per-frame reallocation on the fixed-size
/// video path). `(0, 0, 0)` means unallocated.
float_render_tex_dims: (usize, usize, u32),
/// Path B shader: NV12/NV16/NV24 R8 → RGBA8 (u8 output).
nv_r8_program: GlProgram,
/// Path B shader: NV12/NV16/NV24 R8 → RGBA8 with int8 XOR 0x80 bias.
nv_r8_int8_program: GlProgram,
/// Link-time uniform locations + colorimetry-upload skip for `nv_r8_program`.
nv_r8_uniforms: NvUniformState,
/// Same for `nv_r8_int8_program`.
nv_r8_int8_uniforms: NvUniformState,
/// Texture for the Path-B R8 EGLImage source (TEXTURE_2D, not EXTERNAL_OES).
nv_r8_texture: Texture,
/// EGLImage cache for Path-B R8 source imports (keyed like src_egl_cache).
nv_r8_egl_cache: ImportCache<PlatformImport>,
/// Which path ran for the most recent NV* convert (instrumentation).
pub(super) last_nv_convert_path: NvConvertPath,
/// Zero-copy feed telemetry (see `ConvertStats`). Plain fields — this
/// struct lives on the single-threaded GL worker.
pub(super) convert_stats: super::cache::ConvertStats,
/// NV import failures already warned about (keyed by buffer identity):
/// first occurrence warns, repeats log at debug — an import that fails
/// once fails every frame, and a per-frame warn is log spam.
nv_import_warned: std::collections::HashSet<u64>,
/// Uniform locations per float-path program (see [`FloatQuadLocs`]).
pub(super) float_quad_locs: std::collections::HashMap<u32, FloatQuadLocs>,
/// Static full-screen quad VBOs `(pos, uv)` for the float paths,
/// uploaded once (`STATIC_DRAW`) — previously `BufferData`-re-uploaded
/// on every float draw. `0` = not yet created (lazy, on the first
/// float draw). Deleted in `Drop`.
pub(super) float_quad_pos_vbo: u32,
pub(super) float_quad_uv_vbo: u32,
/// Client preference for NV* path selection (`EDGEFIRST_NV_CONVERT_PATH`).
nv_path_pref: NvPathPref,
/// Colorimetry/performance trade-off (see [`crate::ColorimetryMode`]).
colorimetry_mode: crate::ColorimetryMode,
/// `true` when `EDGEFIRST_COLORIMETRY` pinned the mode for this
/// processor's lifetime — `set_colorimetry_mode` then logs and keeps it.
colorimetry_env_pinned: bool,
/// When `true`, a convert's terminal `glFinish` is skipped so a batch of
/// tiles rendered into one shared destination import syncs only once, via a
/// single `finish_via_fence` at [`flush`](Self::flush). Set for the duration
/// of a single [`convert_deferred`](Self::convert_deferred) and reset
/// unconditionally (even on error) so a subsequent standalone `convert` never
/// silently returns on an unfinished GPU. Always `false` between calls.
pub(super) defer_finish: bool,
/// `true` when one or more `convert_deferred` calls have rendered without a
/// `glFinish` and a [`flush`](Self::flush) (single `finish_via_fence`) is
/// still owed. Read by the CUDA map path to auto-flush before handing the
/// device a buffer whose batched render may still be in flight; cleared by
/// the flush. See [`flush_pending`](Self::flush_pending).
pub(super) pending_flush: bool,
pub(super) gl_context: PlatformDisplay,
}
impl Drop for GLProcessorST {
fn drop(&mut self) {
unsafe {
{
if self.proto_ssbo != 0 {
edgefirst_gl::gl::DeleteBuffers(1, &self.proto_ssbo);
}
if self.float_quad_pos_vbo != 0 {
let ids = [self.float_quad_pos_vbo, self.float_quad_uv_vbo];
edgefirst_gl::gl::DeleteBuffers(2, ids.as_ptr());
}
if let Some(program) = self.proto_repack_compute_program {
edgefirst_gl::gl::DeleteProgram(program);
}
}
}
}
}
/// Emit a warning the first time a draw operation falls back from the
/// DMA-BUF fast path to the CPU readback fallback. The fast path is silent;
/// the slow path is loud (once) so a regression — for example a tensor with
/// a non-aligned pitch or a missing extension — does not silently degrade
/// performance by 10–20× without anyone noticing.
///
/// The message includes the failing call site, the failing setup function,
/// and the underlying error so the user can map it back to the root cause
/// (commonly Mali's 64-byte pitch alignment requirement). Subsequent
/// fallbacks are demoted to debug-level.
fn warn_slow_path_once(call_site: &str, failing_setup: &str, err: &crate::Error) {
use std::sync::Once;
static SLOW_PATH_WARNED: Once = Once::new();
let mut emitted = false;
SLOW_PATH_WARNED.call_once(|| {
log::warn!(
"{call_site}: GL DMA-BUF fast path unavailable, falling back to CPU \
readback (10–20× slower). Cause: {failing_setup} returned {err:?}. \
On Mali Valhall (i.MX 95) this is usually because the destination \
tensor's row pitch is not 64-byte aligned — see \
`ImageProcessor::create_image` for automatic alignment. \
Subsequent fallbacks will be logged at debug level."
);
emitted = true;
});
if !emitted {
log::debug!("{call_site}: GL DMA-BUF fast path unavailable ({failing_setup}: {err:?})");
}
}
/// Reinterpret a `&mut Tensor<i8>` as `&mut Tensor<u8>`.
///
/// # Safety
/// `i8` and `u8` have identical size, alignment, and validity for all bit
/// patterns. `Tensor<T>` stores data behind indirection (DMA-BUF fd, SHM
/// mapping, mmap'd memory, or PBO) — the `T` parameter affects only the
/// typed view returned by `map()`, not the struct layout. The GL backend
/// operates on raw bytes and applies XOR 0x80 bias either in the fragment
/// shader or as a CPU post-process, so the reinterpretation is semantically
/// correct. This transmutation must not be used to access `chroma()` through
/// the returned reference — the chroma `Box<Tensor<T>>` would also be
/// reinterpreted and its drop glue could theoretically differ.
unsafe fn tensor_i8_as_u8_mut(t: &mut Tensor<i8>) -> &mut Tensor<u8> {
&mut *(t as *mut Tensor<i8> as *mut Tensor<u8>)
}
/// Reinterpret a `&Tensor<i8>` as `&Tensor<u8>`.
///
/// # Safety
/// Same rationale as [`tensor_i8_as_u8_mut`]. The returned reference must not
/// be used to access `chroma()`.
unsafe fn tensor_i8_as_u8(t: &Tensor<i8>) -> &Tensor<u8> {
&*(t as *const Tensor<i8> as *const Tensor<u8>)
}
/// Extract `&Tensor<u8>` and `PixelFormat` from a `&TensorDyn` source.
/// For I8 sources, reinterprets the bytes as u8.
fn dyn_to_u8_src(src: &TensorDyn) -> crate::Result<(&Tensor<u8>, PixelFormat)> {
match src {
TensorDyn::U8(t) => {
let fmt = t.format().ok_or(Error::NotAnImage)?;
Ok((t, fmt))
}
TensorDyn::I8(t) => {
let fmt = t.format().ok_or(Error::NotAnImage)?;
// SAFETY: i8/u8 are layout-identical
Ok((unsafe { tensor_i8_as_u8(t) }, fmt))
}
_ => Err(Error::UnsupportedFormat(format!(
"GL backend requires u8 or i8 source, got {:?}",
src.dtype()
))),
}
}
/// Extract `&mut Tensor<u8>`, `PixelFormat`, and `is_int8` from a `&mut TensorDyn` destination.
/// For I8 destinations, reinterprets the bytes as u8 and sets `is_int8 = true`.
fn dyn_to_u8_dst(dst: &mut TensorDyn) -> crate::Result<(&mut Tensor<u8>, PixelFormat, bool)> {
match dst {
TensorDyn::U8(t) => {
let fmt = t.format().ok_or(Error::NotAnImage)?;
Ok((t, fmt, false))
}
TensorDyn::I8(t) => {
let fmt = t.format().ok_or(Error::NotAnImage)?;
// SAFETY: i8/u8 are layout-identical
Ok((unsafe { tensor_i8_as_u8_mut(t) }, fmt, true))
}
_ => Err(Error::UnsupportedFormat(format!(
"GL backend requires u8 or i8 destination, got {:?}",
dst.dtype()
))),
}
}
impl ImageProcessorTrait for GLProcessorST {
fn convert(
&mut self,
src: &TensorDyn,
dst: &mut TensorDyn,
rotation: crate::Rotation,
flip: Flip,
crop: Crop,
) -> crate::Result<()> {
// A view()/batch() destination is lowered to a glViewport/scissor band
// only on the u8/i8 DMA packed path (see `setup_renderbuffer_dma` +
// `convert_to`). For any other GL destination — a non-DMA CPU upload, a
// PBO, or a float render target — that lowering does not exist, so
// decline and let the dispatcher fall back to the CPU backend, which
// writes the sub-region correctly via offset + parent stride.
if dst.view_origin().is_some()
&& !(self.gl_context.transfer_backend.is_zero_copy()
&& dst.memory() == TensorMemory::Dma
&& matches!(
dst.dtype(),
edgefirst_tensor::DType::U8 | edgefirst_tensor::DType::I8
))
{
return Err(Error::NotSupported(
"GL view()/batch() destination is supported only for u8/i8 DMA buffers; \
CPU fallback handles other cases"
.into(),
));
}
let crop = crop.resolve(
src.width().unwrap_or(0),
src.height().unwrap_or(0),
dst.width().unwrap_or(0),
dst.height().unwrap_or(0),
)?;
// F16/F32 destination: check for a GL float render path BEFORE the u8
// extraction functions reject the dtype. When a path is found, dispatch
// to convert_float_to_pbo (stub → NotSupported → CPU fallback). When
// None, fall through to the existing u8 path unchanged.
let dst_dtype = dst.dtype();
if matches!(
dst_dtype,
edgefirst_tensor::DType::F16 | edgefirst_tensor::DType::F32
) {
let src_fmt = src.format().ok_or(Error::NotAnImage)?;
let dst_fmt = dst.format().ok_or(Error::NotAnImage)?;
let support = float_render_support(
self.is_vivante,
self.supports_f32_color,
self.supports_f16_color,
);
// Fused NV*→PlanarRgb-F16 (the model-input convert): two engine
// passes — NV→RGBA full-res into a cached intermediate, then the
// packed float render with the caller's crop/letterbox. Viability
// is pass 2's own classifier verdict on an RGBA source.
if matches!(
src_fmt,
PixelFormat::Nv12 | PixelFormat::Nv16 | PixelFormat::Nv24
) && dst_fmt == PixelFormat::PlanarRgb
&& dst_dtype == edgefirst_tensor::DType::F16
&& classify_float_render(
PixelFormat::Rgba,
dst_fmt,
dst_dtype,
dst.memory(),
support,
) != FloatRenderPath::None
{
return self.convert_nv_to_planar_float_two_pass(src, dst, rotation, flip, crop);
}
let path = classify_float_render(src_fmt, dst_fmt, dst_dtype, dst.memory(), support);
match path {
FloatRenderPath::ZeroCopyF16Nchw => {
return self.convert_float_to_zero_copy(src, dst, rotation, flip, crop);
}
FloatRenderPath::None => {}
_ => {
return self.convert_float_to_pbo(src, dst, path, rotation, flip, crop);
}
}
// path == None: fall through to the u8 path, which will reject
// F16/F32 via dyn_to_u8_dst → CPU fallback (existing behavior).
}
// Capture odd-destination dims before the mutable borrow below, for the
// defense-in-depth wrap at the end (rule #2).
let dst_odd = match (dst.width(), dst.height()) {
(Some(w), Some(h)) if w % 2 != 0 || h % 2 != 0 => Some((w, h)),
_ => None,
};
let (src_u8, src_fmt) = dyn_to_u8_src(src)?;
let (dst_u8, dst_fmt, is_int8) = dyn_to_u8_dst(dst)?;
let result = self.convert_impl(
src_u8, src_fmt, dst_u8, dst_fmt, is_int8, rotation, flip, crop,
);
// Defense-in-depth (rule #2): `Tensor::image` now 64-aligns DMA strides,
// so image()-allocated destinations import fine at any width. But an
// externally-imported destination with an odd, non-64-aligned stride can
// still be rejected by a GPU that requires an aligned EGLImage pitch
// (Mali `BadAlloc`, Vivante `BadAccess`). Surface such EGL/GL failures as
// a descriptive `NotSupported` that PRESERVES the underlying error and
// flags it as a platform-consistency limitation, rather than leaking a
// raw `EGL(BadAlloc)`. (The F16/F32 float paths return earlier; their
// destinations are 64-aligned by the same allocator fix.)
match result {
Err(e) if dst_odd.is_some() && matches!(e, Error::EGL(_) | Error::OpenGl(_)) => {
let (w, h) = dst_odd.unwrap();
Err(Error::NotSupported(format!(
"Conversion failed with {e:?} and target tensor has odd \
dimensions {w}x{h}, which is not supported by all platforms"
)))
}
other => other,
}
}
fn convert_deferred(
&mut self,
src: &TensorDyn,
dst: &mut TensorDyn,
rotation: crate::Rotation,
flip: Flip,
crop: Crop,
) -> Result<(), crate::Error> {
// Render without the terminal `glFinish` (gated in `convert_to` by
// `defer_finish`), leaving a single `finish_via_fence` owed at `flush`.
// The flag resets unconditionally so a later standalone `convert` always
// finishes; only a successful deferred render arms `pending_flush`.
self.defer_finish = true;
let result = self.convert(src, dst, rotation, flip, crop);
self.defer_finish = false;
if result.is_ok() {
self.pending_flush = true;
}
result
}
fn flush(&mut self) -> Result<(), crate::Error> {
let _span = tracing::trace_span!("image.flush.gl", pending = self.pending_flush).entered();
self.flush_pending();
Ok(())
}
fn draw_decoded_masks(
&mut self,
dst: &mut TensorDyn,
detect: &[DetectBox],
segmentation: &[Segmentation],
overlay: crate::MaskOverlay<'_>,
) -> Result<(), crate::Error> {
let bg = overlay.background.map(|bg| dyn_to_u8_src(bg)).transpose()?;
let (dst_u8, dst_fmt, _is_int8) = dyn_to_u8_dst(dst)?;
self.draw_decoded_masks_impl(
dst_u8,
dst_fmt,
detect,
segmentation,
overlay.opacity,
bg,
overlay.color_mode,
)
}
fn draw_proto_masks(
&mut self,
dst: &mut TensorDyn,
detect: &[DetectBox],
proto_data: &ProtoData,
overlay: crate::MaskOverlay<'_>,
) -> crate::Result<()> {
let bg = overlay.background.map(|bg| dyn_to_u8_src(bg)).transpose()?;
let (dst_u8, dst_fmt, _is_int8) = dyn_to_u8_dst(dst)?;
self.draw_proto_masks_impl(
dst_u8,
dst_fmt,
detect,
proto_data,
overlay.opacity,
bg,
overlay.color_mode,
)
}
fn set_class_colors(&mut self, colors: &[[u8; 4]]) -> crate::Result<()> {
if colors.is_empty() {
return Ok(());
}
let mut colors_f32 = colors
.iter()
.map(|c| {
[
c[0] as f32 / 255.0,
c[1] as f32 / 255.0,
c[2] as f32 / 255.0,
c[3] as f32 / 255.0,
]
})
.take(20)
.collect::<Vec<[f32; 4]>>();
self.segmentation_program
.load_uniform_4fv(c"colors", &colors_f32)?;
self.instanced_segmentation_program
.load_uniform_4fv(c"colors", &colors_f32)?;
self.proto_segmentation_program
.load_uniform_4fv(c"colors", &colors_f32)?;
self.proto_segmentation_int8_nearest_program
.load_uniform_4fv(c"colors", &colors_f32)?;
self.proto_segmentation_int8_bilinear_program
.load_uniform_4fv(c"colors", &colors_f32)?;
self.proto_segmentation_f32_program
.load_uniform_4fv(c"colors", &colors_f32)?;
colors_f32.iter_mut().for_each(|c| {
c[3] = 1.0; // set alpha to 1.0 for color rendering
});
self.color_program
.load_uniform_4fv(c"colors", &colors_f32)?;
Ok(())
}
}
/// Whether `EDGEFIRST_ALLOW_SOFTWARE_GL=1` is set, opting in to running the GL
/// backend on a software renderer (Mesa llvmpipe/softpipe/swrast).
///
/// Off by default and in production; the CI coverage lane sets it so the GL
/// render path executes on llvmpipe where no GPU exists.
fn software_gl_override_enabled() -> bool {
std::env::var_os("EDGEFIRST_ALLOW_SOFTWARE_GL").is_some_and(|v| v == "1")
}
/// Decide whether to reject an initialized GL context for being a software
/// renderer. Pure so it is unit-testable without touching the environment or a
/// real GL context: reject only when the renderer is software AND the override
/// is not enabled.
fn should_reject_software_gl(is_software_renderer: bool, override_enabled: bool) -> bool {
is_software_renderer && !override_enabled
}
/// GL_RENDERER-derived driver traits that feed per-driver policy.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
struct RendererTraits {
/// Verisilicon/Vivante core — GPU-hang workarounds + Full serialization.
vivante: bool,
/// Software rasterizer (llvmpipe/softpipe/swrast) — rejected unless the
/// coverage-lane override is set.
software: bool,
/// Virtualized/paravirtual GPU — concurrent GL across contexts
/// mis-renders (observed: Apple Paravirtual device on macOS CI runners);
/// gets the Full serialization policy.
virtual_gpu: bool,
}
/// Capability probe results from a freshly-current GL context
/// (`gl_check_support`): extension-derived feature flags plus the
/// GL_RENDERER-derived driver traits.
struct GlSupport {
has_float_linear: bool,
has_bgra: bool,
renderer: RendererTraits,
supports_f32_color: bool,
supports_f16_color: bool,
}
/// `glReadPixels` the bound read-framebuffer into `out`, honoring the ES 3
/// guarantee: only `RGBA`/`UNSIGNED_BYTE` plus ONE implementation-defined
/// pair are accepted. Mesa and the embedded drivers take `RGB`/`RED`
/// directly; ANGLE/Metal (and V3D) reject them with `GL_INVALID_OPERATION`.
/// When the direct read is unsupported, read an RGBA scratch and repack the
/// leading channels (the FBO attachment has the destination's channel
/// layout, so RGB keeps rgb, RED keeps r).
///
/// Plain `glReadPixels`, NOT `glReadnPixels`: the robust variant is an
/// ES 3.2 entry point and ANGLE/Metal (ES 3.0 max) rejects it at
/// validation. `out` is at least `w*h*channels` bytes and reads are tightly
/// packed (`PACK_ALIGNMENT=1` at init), so the bounds the robust variant
/// checked hold by construction.
///
/// # Safety
/// Must run on the GL thread with a complete read framebuffer bound and
/// `ReadBuffer` selected.
///
/// `scratch` is the caller's reusable RGBA staging buffer
/// (`GLProcessorST::readback_scratch`) — grown on demand and kept at its
/// high-water mark, so the fallback path costs no per-call allocation
/// after the first read of a given size.
unsafe fn read_pixels_into(w: usize, h: usize, format: u32, scratch: &mut Vec<u8>, out: &mut [u8]) {
let direct = format == edgefirst_gl::gl::RGBA || {
let mut impl_fmt = 0i32;
let mut impl_type = 0i32;
edgefirst_gl::gl::GetIntegerv(
edgefirst_gl::gl::IMPLEMENTATION_COLOR_READ_FORMAT,
&mut impl_fmt,
);
edgefirst_gl::gl::GetIntegerv(
edgefirst_gl::gl::IMPLEMENTATION_COLOR_READ_TYPE,
&mut impl_type,
);
impl_fmt as u32 == format && impl_type as u32 == edgefirst_gl::gl::UNSIGNED_BYTE
};
if direct {
edgefirst_gl::gl::ReadPixels(
0,
0,
w as i32,
h as i32,
format,
edgefirst_gl::gl::UNSIGNED_BYTE,
out.as_mut_ptr() as *mut c_void,
);
return;
}
let channels = match format {
edgefirst_gl::gl::RGB => 3,
edgefirst_gl::gl::RED => 1,
_ => 4,
};
if scratch.len() < w * h * 4 {
scratch.resize(w * h * 4, 0);
}
edgefirst_gl::gl::ReadPixels(
0,
0,
w as i32,
h as i32,
edgefirst_gl::gl::RGBA,
edgefirst_gl::gl::UNSIGNED_BYTE,
scratch.as_mut_ptr() as *mut c_void,
);
for (px, dst_px) in scratch.chunks_exact(4).zip(out.chunks_exact_mut(channels)) {
dst_px.copy_from_slice(&px[..channels]);
}
}
/// Classify a GL_RENDERER string into driver-policy traits. Pure —
/// unit-testable without a GL context.
fn classify_renderer(renderer: &str) -> RendererTraits {
let lower = renderer.to_ascii_lowercase();
RendererTraits {
vivante: lower.contains("vivante") || lower.contains("gc7000") || lower.contains("galcore"),
software: lower.contains("llvmpipe")
|| lower.contains("softpipe")
|| lower.contains("swrast")
|| lower.contains("software rasterizer"),
virtual_gpu: lower.contains("paravirtual") || lower.contains("virtio"),
}
}
impl GLProcessorST {
/// Issue the single batched GPU sync if a `convert_deferred` is still owed,
/// then clear the pending flag. No-op when nothing is pending. Used by both
/// [`flush`](ImageProcessorTrait::flush) and the CUDA map path (which
/// auto-flushes before handing the device a possibly-in-flight buffer).
///
/// # Safety contract
/// Must run on the GL worker thread that owns the context (it is, being
/// driven from the worker loop under `GL_MUTEX`).
pub(super) fn flush_pending(&mut self) {
if self.pending_flush {
// SAFETY: called on the context-owning GL worker thread.
unsafe { float::finish_via_fence() };
self.pending_flush = false;
}
}
pub fn new(kind: Option<EglDisplayKind>) -> Result<GLProcessorST, crate::Error> {
// Display bring-up goes through the platform seam — the contract a
// future platform (Windows/ANGLE) implements instead of forking this
// engine. On Linux this delegates straight to `GlContext::new`.
let gl_context = Platform::init_display(kind)?;
// Load the GL function pointers exactly once per process — `edgefirst_gl`
// bindings are gl_generator `static mut` function-pointer tables, so
// re-running `load_with` per construction would be a data race with
// unlocked workers. Platform-routed: Linux loads via this display's
// eglGetProcAddress; macOS loaded at shared-display init already.
Platform::load_gl_once(&gl_context);
let GlSupport {
has_float_linear,
has_bgra,
renderer:
RendererTraits {
vivante: is_vivante,
software: is_software_renderer,
virtual_gpu: is_virtual_gpu,
},
supports_f32_color,
supports_f16_color,
} = Self::gl_check_support()?;
// Software renderers (llvmpipe, softpipe, swrast) are CPU-based OpenGL
// implementations that are slower and less capable than our native CPU
// backend. Reject them early — the caller falls back to CPU automatically.
//
// `EDGEFIRST_ALLOW_SOFTWARE_GL=1` overrides the rejection. It exists
// for the CI coverage lane, which runs the GL render path (e.g. the
// float PBO roundtrips) on Mesa llvmpipe where no GPU is available —
// the rendered output is numerically identical to a hardware GPU since
// it runs the same GLSL. Production never sets it, so the default
// (reject software GL, fall back to CPU) is unchanged.
if should_reject_software_gl(is_software_renderer, software_gl_override_enabled()) {
return Err(crate::Error::NotSupported(
"software OpenGL renderer detected (llvmpipe/softpipe/swrast); \
GL backend disabled — check EGL ICD configuration if a \
hardware GPU is expected (set EDGEFIRST_ALLOW_SOFTWARE_GL=1 \
to override, e.g. for coverage on Mesa llvmpipe)"
.into(),
));
}
if is_software_renderer {
log::warn!(
"software OpenGL renderer in use (EDGEFIRST_ALLOW_SOFTWARE_GL=1); \
slower than the CPU backend — intended for CI coverage only"
);
}
// Uploads and downloads are all packed with no alignment requirements
unsafe {
edgefirst_gl::gl::PixelStorei(edgefirst_gl::gl::PACK_ALIGNMENT, 1);
edgefirst_gl::gl::PixelStorei(edgefirst_gl::gl::UNPACK_ALIGNMENT, 1);
}
// External-OES sampler programs exist only where the platform's
// import binding uses them (Linux Path A); ANGLE/Metal rejects the
// extension at shader-compile time, so they are not built there.
let texture_program_planar = if Platform::EXTERNAL_OES {
Some(GlProgram::new(
generate_vertex_shader(),
generate_planar_rgb_shader(),
)?)
} else {
None
};
let texture_program =
GlProgram::new(generate_vertex_shader(), generate_texture_fragment_shader())?;
let texture_program_yuv = if Platform::EXTERNAL_OES {
Some(GlProgram::new(
generate_vertex_shader(),
generate_texture_fragment_shader_yuv(),
)?)
} else {
None
};
let texture_int8_program =
GlProgram::new(generate_vertex_shader(), generate_texture_int8_shader())?;
let texture_int8_program_yuv = if Platform::EXTERNAL_OES {
Some(GlProgram::new(
generate_vertex_shader(),
generate_texture_int8_shader_yuv(),
)?)
} else {
None
};
let yuyv_program_2d = GlProgram::new(
generate_vertex_shader(),
super::shaders_common::YUYV_RGBA_2D_FRAGMENT,
)?;
let yuyv_2d_locs = unsafe {
edgefirst_gl::gl::UseProgram(yuyv_program_2d.id);
// Constant sampler binding resolved at link (B6 pattern).
let tex = edgefirst_gl::gl::GetUniformLocation(yuyv_program_2d.id, c"tex".as_ptr());
edgefirst_gl::gl::Uniform1i(tex, 0);
[
edgefirst_gl::gl::GetUniformLocation(yuyv_program_2d.id, c"src_size".as_ptr()),
edgefirst_gl::gl::GetUniformLocation(yuyv_program_2d.id, c"y_offset".as_ptr()),
edgefirst_gl::gl::GetUniformLocation(yuyv_program_2d.id, c"y_scale".as_ptr()),
edgefirst_gl::gl::GetUniformLocation(yuyv_program_2d.id, c"c_vr".as_ptr()),
edgefirst_gl::gl::GetUniformLocation(yuyv_program_2d.id, c"c_ug".as_ptr()),
edgefirst_gl::gl::GetUniformLocation(yuyv_program_2d.id, c"c_vg".as_ptr()),
edgefirst_gl::gl::GetUniformLocation(yuyv_program_2d.id, c"c_ub".as_ptr()),
]
};
let segmentation_program =
GlProgram::new(generate_vertex_shader(), generate_segmentation_shader())?;
segmentation_program.load_uniform_4fv(c"colors", &DEFAULT_COLORS)?;
let instanced_segmentation_program = GlProgram::new(
generate_vertex_shader(),
generate_instanced_segmentation_shader(),
)?;
instanced_segmentation_program.load_uniform_4fv(c"colors", &DEFAULT_COLORS)?;
// Existing f16 proto shader (RGBA16F, 4 protos per layer)
let proto_segmentation_program = GlProgram::new(
generate_vertex_shader(),
generate_proto_segmentation_shader(),
)?;
proto_segmentation_program.load_uniform_4fv(c"colors", &DEFAULT_COLORS)?;
// Int8 proto shaders (R8I, 1 proto per layer, 32 layers)
let proto_segmentation_int8_nearest_program = GlProgram::new(
generate_vertex_shader(),
generate_proto_segmentation_shader_int8_nearest(),
)?;
proto_segmentation_int8_nearest_program.load_uniform_4fv(c"colors", &DEFAULT_COLORS)?;
let proto_segmentation_int8_bilinear_program = GlProgram::new(
generate_vertex_shader(),
generate_proto_segmentation_shader_int8_bilinear(),
)?;
proto_segmentation_int8_bilinear_program.load_uniform_4fv(c"colors", &DEFAULT_COLORS)?;
let proto_dequant_int8_program = GlProgram::new(
generate_vertex_shader(),
generate_proto_dequant_shader_int8(),
)?;
// F32 proto shader (R32F, 1 proto per layer, 32 layers)
let proto_segmentation_f32_program = GlProgram::new(
generate_vertex_shader(),
generate_proto_segmentation_shader_f32(),
)?;
proto_segmentation_f32_program.load_uniform_4fv(c"colors", &DEFAULT_COLORS)?;
let color_program = GlProgram::new(generate_vertex_shader(), generate_color_shader())?;
color_program.load_uniform_4fv(c"colors", &DEFAULT_COLORS)?;
// Int8 variant of the existing planar RGB shader (for planar RGB int8 destinations).
let texture_program_planar_int8 = if Platform::EXTERNAL_OES {
Some(GlProgram::new(
generate_vertex_shader(),
generate_planar_rgb_int8_shader(),
)?)
} else {
None
};
// Planar RGB shaders with sampler2D (for two-pass NV12→RGBA→PlanarRgb on Vivante)
let texture_program_planar_2d =
GlProgram::new(generate_vertex_shader(), generate_planar_rgb_shader_2d())?;
let texture_program_planar_int8_2d = GlProgram::new(
generate_vertex_shader(),
generate_planar_rgb_int8_shader_2d(),
)?;
// RGB packing shaders (2D only — used in pass 2 of two-pass pipeline)
let packed_rgba8_program_2d =
GlProgram::new(generate_vertex_shader(), generate_packed_rgba8_shader_2d())?;
let packed_rgba8_int8_program_2d = GlProgram::new(
generate_vertex_shader(),
generate_packed_rgba8_int8_shader_2d(),
)?;
// Float render-to-PBO programs. Both are full-viewport fragment
// shaders driven by `gl_FragCoord`; the standard vertex shader emits a
// full-screen quad so every packed output texel is visited. Crop and
// letterbox are entirely uniform-driven (src_rect_uv/dst_rect_px/
// pad_color), matching the macOS IOSurface contract.
let float_f32_nhwc_program =
GlProgram::new(generate_vertex_shader(), generate_packed_f32_nhwc_shader())?;
let float_f16_nchw_program = GlProgram::new(
generate_vertex_shader(),
generate_planar_rgb_f16_packed_shader(),
)?;
// Path B: NV12/NV16/NV24 → RGBA via R8 texelFetch shader (ES 3.0 core, no extension).
let nv_r8_program =
GlProgram::new(generate_vertex_shader(), generate_nv_to_rgba_shader_2d())?;
let nv_r8_int8_program = GlProgram::new(
generate_vertex_shader(),
generate_nv_to_rgba_int8_shader_2d(),
)?;
// Resolve uniform locations once at link time (the NV draw is per-frame)
// and upload the constant sampler bindings while the programs are fresh:
// pass-2 packing samples the intermediate on unit 1, planar-2d on unit 0.
let nv_r8_uniforms = NvUniformState::resolve(&nv_r8_program);
let nv_r8_int8_uniforms = NvUniformState::resolve(&nv_r8_int8_program);
packed_rgba8_program_2d.load_uniform_1i(c"tex", 1)?;
packed_rgba8_int8_program_2d.load_uniform_1i(c"tex", 1)?;
texture_program_planar_2d.load_uniform_1i(c"tex", 0)?;
texture_program_planar_int8_2d.load_uniform_1i(c"tex", 0)?;
let camera_eglimage_texture = Texture::new();
let camera_normal_texture = Texture::new();
let render_texture = Texture::new();
let draw_render_texture = Texture::new();
let segmentation_texture = Texture::new();
let proto_texture = Texture::new();
let proto_dequant_texture = Texture::new();
let vertex_buffer = Buffer::new(0, 3, 100);
let texture_buffer = Buffer::new(1, 2, 100);
// EGLImage cache capacity (per cache: src / dst / nv_r8). The key carries
// geometry, so a pool buffer reused at N distinct sizes needs N live
// EGLImages to avoid evict/re-import churn; a parallel decode pool wants
// headroom for (pool slots × distinct sizes). Capacity is the eviction
// bound only — EGLImages are lightweight views into the tensor's existing
// DMA-BUF (no pixel copy) and are created on demand, so a large default is
// free for fixed-dimension workloads (live camera) that only ever use a
// size or two. Override with EDGEFIRST_EGL_CACHE_CAPACITY for high-
// cardinality varied-size streams (e.g. dataset validation).
const DEFAULT_EGL_CACHE_CAPACITY: usize = 64;
let egl_cache_capacity = std::env::var("EDGEFIRST_EGL_CACHE_CAPACITY")
.ok()
.and_then(|v| v.parse::<usize>().ok())
.filter(|&c| c > 0)
.unwrap_or(DEFAULT_EGL_CACHE_CAPACITY);
// NV* conversion-path preference. `auto` (default) prefers the portable,
// colorimetry-exact in-shader ShaderR8 path; `sampler`/`shader` force a
// path for benchmarking / platform bring-up (an impossible force warns
// and falls back). Mirrors the EDGEFIRST_FORCE_TRANSFER idiom below.
let nv_path_pref = match std::env::var("EDGEFIRST_NV_CONVERT_PATH") {
Ok(v) => match v.to_ascii_lowercase().as_str() {
"sampler" | "external" | "a" => NvPathPref::ForceSampler,
"shader" | "r8" | "b" => NvPathPref::ForceShader,
"auto" | "" => NvPathPref::Auto,
other => {
log::warn!(
"EDGEFIRST_NV_CONVERT_PATH={other:?} not recognised \
(expected sampler|shader|auto), using auto"
);
NvPathPref::Auto
}
},
Err(_) => NvPathPref::Auto,
};
if nv_path_pref != NvPathPref::Auto {
log::info!("EDGEFIRST_NV_CONVERT_PATH override: {nv_path_pref:?}");
}
// Colorimetry/performance trade-off. The env var pins the mode for the
// processor's lifetime (set_colorimetry_mode logs and keeps it);
// otherwise the config default is Fast (issue #106 policy) and
// `set_colorimetry_mode` may change it.
let colorimetry_env = match std::env::var("EDGEFIRST_COLORIMETRY") {
Ok(v) => match v.to_ascii_lowercase().as_str() {
"exact" => Some(crate::ColorimetryMode::Exact),
"fast" => Some(crate::ColorimetryMode::Fast),
"" => None,
other => {
log::warn!(
"EDGEFIRST_COLORIMETRY={other:?} not recognised \
(expected fast|exact), ignoring"
);
None
}
},
Err(_) => None,
};
if let Some(mode) = colorimetry_env {
log::info!("EDGEFIRST_COLORIMETRY override: {mode:?}");
}
let mut converter = GLProcessorST {
gl_context,
texture_program,
texture_program_yuv,
texture_int8_program,
texture_int8_program_yuv,
texture_program_planar,
texture_program_planar_int8,
yuyv_program_2d,
yuyv_2d_locs,
packed_rgba8_program_2d,
packed_rgba8_int8_program_2d,
texture_program_planar_2d,
texture_program_planar_int8_2d,
float_f32_nhwc_program,
float_f16_nchw_program,
float_render_texture: Texture::new(),
float_render_tex_dims: (0, 0, 0),
camera_eglimage_texture,
camera_normal_texture,
segmentation_texture,
proto_texture,
proto_segmentation_int8_nearest_program,
proto_segmentation_int8_bilinear_program,
proto_dequant_int8_program,
proto_segmentation_f32_program,
has_float_linear,
has_bgra,
supports_f32_color,
supports_f16_color,
int8_interpolation_mode: Int8InterpolationMode::Bilinear,
proto_dequant_texture,
proto_dequant_tex_dims: (0, 0, 0, 0),
proto_dequant_fbo: FrameBuffer::new(),
proto_quad_locs: std::cell::Cell::new((0, -1, -1)),
vertex_buffer,
texture_buffer,
convert_fbo: FrameBuffer::new(),
draw_fbo: FrameBuffer::new(),
draw_render_texture,
src_egl_cache: ImportCache::new(egl_cache_capacity),
dst_egl_cache: ImportCache::new(egl_cache_capacity),
bgra_warned: false,
readback_scratch: Vec::new(),
is_vivante,
is_virtual_gpu,
use_renderbuffer: std::env::var("EDGEFIRST_OPENGL_RENDERSURFACE")
.map(|v| v == "1")
.unwrap_or(false),
packed_rgb_intermediate_tex: Texture::new(),
packed_rgb_fbo: FrameBuffer::new(),
packed_rgb_intermediate_size: (0, 0),
render_texture,
segmentation_program,
instanced_segmentation_program,
proto_segmentation_program,
color_program,
cached_opacity: f32::NAN, // sentinel: forces first set_opacity_uniform to initialize all shaders
proto_tex_dims: (0, 0, 0, 0),
proto_repack_compute_program: None,
proto_compute_locs: (-1, -1, -1),
proto_ssbo: 0,
proto_ssbo_size: 0,
nv_r8_program,
nv_r8_int8_program,
nv_r8_uniforms,
nv_r8_int8_uniforms,
nv_r8_texture: Texture::new(),
nv_r8_egl_cache: ImportCache::new(egl_cache_capacity),
last_nv_convert_path: NvConvertPath::None,
convert_stats: Default::default(),
nv_import_warned: std::collections::HashSet::new(),
float_quad_locs: std::collections::HashMap::new(),
float_quad_pos_vbo: 0,
float_quad_uv_vbo: 0,
nv_path_pref,
colorimetry_mode: colorimetry_env.unwrap_or_default(),
colorimetry_env_pinned: colorimetry_env.is_some(),
defer_finish: false,
pending_flush: false,
};
check_gl_error(function!(), line!())?;
// Compile compute shader for proto repack if GLES 3.1 is available.
// Enabled via EDGEFIRST_PROTO_COMPUTE=1 while validating on target GPUs.
let compute_enabled = converter.gl_context.has_compute
&& std::env::var("EDGEFIRST_PROTO_COMPUTE")
.map(|v| v == "1")
.unwrap_or(false);
if compute_enabled {
match Self::compile_compute_program(generate_proto_repack_compute_shader()) {
Ok(program) => {
log::info!("Proto repack compute shader compiled successfully");
converter.proto_repack_compute_program = Some(program);
unsafe {
converter.proto_compute_locs = (
edgefirst_gl::gl::GetUniformLocation(program, c"width".as_ptr()),
edgefirst_gl::gl::GetUniformLocation(program, c"height".as_ptr()),
edgefirst_gl::gl::GetUniformLocation(program, c"num_protos".as_ptr()),
);
}
let mut ssbo = 0u32;
unsafe { edgefirst_gl::gl::GenBuffers(1, &mut ssbo) };
converter.proto_ssbo = ssbo;
}
Err(e) => {
log::warn!("Proto repack compute shader failed: {e}; using CPU fallback");
}
}
}
log::debug!(
"GLProcessorST: DMA destination attachment mode: {}",
if converter.use_renderbuffer {
"renderbuffer (EDGEFIRST_OPENGL_RENDERSURFACE=1)"
} else {
"texture (default)"
}
);
// Verify DMA-buf actually works (catches NVIDIA discrete GPUs where
// EGLImage creation succeeds but rendered data is all zeros)
if converter.gl_context.transfer_backend.is_dma() && !converter.verify_dma_buf_roundtrip() {
log::info!("DMA-buf verification failed — falling back to PBO transfers");
// Structured twin of the log line: this downgrade silently costs
// every future convert its zero-copy path, so subscribers
// (profiler, telemetry) get a machine-readable event too.
tracing::event!(
tracing::Level::INFO,
from = "dmabuf",
to = "pbo",
"image.convert.gl.transfer_downgrade"
);
converter.gl_context.transfer_backend = TransferBackend::Pbo;
}
// If DMA-buf failed/unavailable but GL is alive, use PBO transfers.
// Software renderers never reach here — they are rejected above.
if converter.gl_context.transfer_backend == TransferBackend::Sync {
log::info!("Upgrading transfer backend from Sync to Pbo (GL context available)");
converter.gl_context.transfer_backend = TransferBackend::Pbo;
}
// Allow env-var override for benchmarking specific transfer paths.
// Values: "dmabuf", "pbo", "sync" (case-insensitive).
if let Ok(val) = std::env::var("EDGEFIRST_FORCE_TRANSFER") {
let forced = match val.to_ascii_lowercase().as_str() {
"dmabuf" | "dma" => Some(TransferBackend::DmaBuf),
"pbo" => Some(TransferBackend::Pbo),
"sync" => Some(TransferBackend::Sync),
other => {
log::warn!(
"EDGEFIRST_FORCE_TRANSFER={other:?} not recognised \
(expected dmabuf|pbo|sync), ignoring"
);
None
}
};
if let Some(backend) = forced {
log::info!(
"EDGEFIRST_FORCE_TRANSFER override: {:?} → {backend:?}",
converter.gl_context.transfer_backend
);
converter.gl_context.transfer_backend = backend;
}
}
log::debug!(
"GLConverter created (transfer={:?})",
converter.gl_context.transfer_backend,
);
Ok(converter)
}
/// Verify that DMA-buf EGLImage round-trip actually works on this GPU.
///
/// Renders a solid red quad to a 64x64 DMA-buf-backed RGBA texture via
/// EGLImage, then reads it back and checks that the center pixel is red.
/// Returns `true` if the data round-trips correctly.
///
/// This catches GPUs like NVIDIA discrete where `eglCreateImage` from
/// `dma_heap` fds succeeds but the rendered data is all zeros.
fn verify_dma_buf_roundtrip(&mut self) -> bool {
// Allocate a 64x64 RGBA DMA source tensor and fill it with solid red
let src = match Tensor::<u8>::image(
64,
64,
PixelFormat::Rgba,
Some(TensorMemory::Dma),
edgefirst_tensor::CpuAccess::Write,
) {
Ok(img) => img,
Err(e) => {
log::info!("verify_dma_buf_roundtrip: failed to allocate DMA source: {e}");
return false;
}
};
{
let mut map = match src.map_write() {
Ok(m) => m,
Err(e) => {
log::info!("verify_dma_buf_roundtrip: failed to map DMA source: {e}");
return false;
}
};
for pixel in map.chunks_exact_mut(4) {
pixel[0] = 255; // R
pixel[1] = 0; // G
pixel[2] = 0; // B
pixel[3] = 255; // A
}
}
// Allocate a 64x64 RGBA DMA destination tensor
let mut dst = match Tensor::<u8>::image(
64,
64,
PixelFormat::Rgba,
Some(TensorMemory::Dma),
edgefirst_tensor::CpuAccess::Read,
) {
Ok(img) => img,
Err(e) => {
log::info!("verify_dma_buf_roundtrip: failed to allocate DMA destination: {e}");
return false;
}
};
// Run the full DMA-buf EGLImage render pipeline (RGBA→RGBA DMA is a
// single-pass zero-copy plan through the engine).
if let Err(e) = self.convert_via_engine(
&mut dst,
PixelFormat::Rgba,
&src,
PixelFormat::Rgba,
false,
Rotation::None,
Flip::None,
ResolvedCrop::no_crop(),
) {
log::info!("verify_dma_buf_roundtrip: convert failed: {e}");
return false;
}
// Read back the center pixel at (32, 32) from the destination
let map = match dst.map_read() {
Ok(m) => m,
Err(e) => {
log::info!("verify_dma_buf_roundtrip: failed to map DMA destination: {e}");
return false;
}
};
let offset = (32 * 64 + 32) * 4;
if map.len() < offset + 4 {
log::info!("verify_dma_buf_roundtrip: destination buffer too small");
return false;
}
let r = map[offset];
let g = map[offset + 1];
let b = map[offset + 2];
let a = map[offset + 3];
let pass = r > 250 && g < 5 && b < 5 && a > 250;
if pass {
log::info!("verify_dma_buf_roundtrip: PASSED (center pixel RGBA={r},{g},{b},{a})");
} else {
log::info!(
"verify_dma_buf_roundtrip: FAILED (center pixel RGBA={r},{g},{b},{a}, \
expected ~255,0,0,255)"
);
}
pass
}
/// Sets the interpolation mode for int8 proto textures.
pub fn set_int8_interpolation_mode(&mut self, mode: Int8InterpolationMode) {
self.int8_interpolation_mode = mode;
log::debug!("Int8 interpolation mode set to {:?}", mode);
}
/// Sets the colorimetry/performance trade-off (see
/// [`crate::ColorimetryMode`]). When `EDGEFIRST_COLORIMETRY` pinned the
/// mode at construction, the env value wins: this logs and keeps it.
pub fn set_colorimetry_mode(&mut self, mode: crate::ColorimetryMode) {
if self.colorimetry_env_pinned {
if mode != self.colorimetry_mode {
log::info!(
"ColorimetryMode::{mode:?} requested but EDGEFIRST_COLORIMETRY pins \
{:?} — keeping the env override",
self.colorimetry_mode
);
}
return;
}
self.colorimetry_mode = mode;
log::debug!("Colorimetry mode set to {:?}", mode);
}
/// Snapshot the EGLImage cache counters (src, dst, NV R8).
///
/// Steady-state tests capture this after warmup and after an N-frame
/// loop and assert `total_misses()` stays flat — the cache-behavior
/// equality gate for GL refactors.
pub(crate) fn egl_cache_stats(&self) -> GlCacheStats {
GlCacheStats {
src: self.src_egl_cache.stats(),
dst: self.dst_egl_cache.stats(),
nv_r8: self.nv_r8_egl_cache.stats(),
}
}
pub(crate) fn convert_stats(&self) -> super::cache::ConvertStats {
self.convert_stats
}
/// Convert without the terminal CPU sync, exporting a native fence fd
/// that signals when the GPU work completes — the GL→NPU handoff.
///
/// Uses the same `defer_finish` mechanism as batching to skip the
/// pure-GPU tails' sync; paths that read back to the CPU (PBO/upload
/// destinations) sync internally regardless, so the fence degenerates
/// to already-signaled there — correct, just no faster than `convert`.
/// When the platform has no native fence (`Ok(None)` / export error)
/// the blocking contract is restored with an explicit `glFinish`.
pub(crate) fn convert_fenced(
&mut self,
src: &TensorDyn,
dst: &mut TensorDyn,
rotation: crate::Rotation,
flip: Flip,
crop: Crop,
) -> Result<Option<std::os::fd::OwnedFd>, crate::Error> {
use crate::ImageProcessorTrait as _;
self.defer_finish = true;
let result = self.convert(src, dst, rotation, flip, crop);
self.defer_finish = false;
result?;
match Platform::export_completion_fence(&self.gl_context) {
Ok(Some(fd)) => Ok(Some(fd)),
Ok(None) => {
unsafe { edgefirst_gl::gl::Finish() };
check_gl_error(function!(), line!())?;
Ok(None)
}
Err(e) => {
// A failed export must not skip the sync — fall back to
// the blocking contract rather than hand back a dst the
// GPU may still be writing.
log::debug!("native fence export failed ({e:?}); falling back to glFinish");
unsafe { edgefirst_gl::gl::Finish() };
check_gl_error(function!(), line!())?;
Ok(None)
}
}
}
// Internal methods operating on Tensor<u8> + PixelFormat directly.
#[allow(clippy::too_many_arguments)]
pub(super) fn convert_impl(
&mut self,
src: &Tensor<u8>,
src_fmt: PixelFormat,
dst: &mut Tensor<u8>,
dst_fmt: PixelFormat,
is_int8: bool,
rotation: crate::Rotation,
flip: Flip,
crop: ResolvedCrop,
) -> crate::Result<()> {
let _span = tracing::trace_span!(
"image.convert.gl",
?src_fmt,
?dst_fmt,
is_int8,
src_memory = ?src.memory(),
dst_memory = ?dst.memory(),
// Recorded at the source-feed site: import | pbo | upload —
// the zero-copy observable (see ConvertStats).
src_feed = tracing::field::Empty,
)
.entered();
if !Self::check_src_format_supported(self.gl_context.transfer_backend, src, src_fmt) {
if src_fmt == PixelFormat::Vyuy
&& self.gl_context.transfer_backend.is_dma()
&& src.memory() == TensorMemory::Dma
{
log::warn!(
"VYUY format not supported via EGL DMA-BUF import; \
falling back to CPU/G2D path"
);
}
return Err(crate::Error::NotSupported(format!(
"Opengl doesn't support {src_fmt} source texture",
)));
}
if !Self::check_dst_format_supported(
self.gl_context.transfer_backend,
dst,
dst_fmt,
is_int8,
self.has_bgra,
) {
return Err(crate::Error::NotSupported(format!(
"Opengl doesn't support {dst_fmt} destination texture",
)));
}
log::debug!(
"dst tensor: {:?} src tensor :{:?}",
dst.memory(),
src.memory()
);
check_gl_error(function!(), line!())?;
log::trace!(
"GL convert_impl: {src_fmt}→{dst_fmt} int8={is_int8} \
src_mem={:?} dst_mem={:?} transfer={:?}",
src.memory(),
dst.memory(),
self.gl_context.transfer_backend,
);
self.convert_via_engine(dst, dst_fmt, src, src_fmt, is_int8, rotation, flip, crop)
}
/// The single u8/i8 convert engine: classify the destination
/// ([`super::render::lower_dst`]), pick the render plan
/// ([`super::render::plan_convert`]), then `bind_dst` → render →
/// readback. The two-pass plans delegate to their render strategies;
/// every single-pass convert — DMA, Mem, or PBO on either side — runs
/// the same code.
#[allow(clippy::too_many_arguments)]
fn convert_via_engine(
&mut self,
dst: &mut Tensor<u8>,
dst_fmt: PixelFormat,
src: &Tensor<u8>,
src_fmt: PixelFormat,
is_int8: bool,
rotation: crate::Rotation,
flip: Flip,
crop: ResolvedCrop,
) -> crate::Result<()> {
let lowering = super::render::lower_dst(
self.gl_context.transfer_backend.is_zero_copy(),
dst.memory(),
);
let plan = super::render::plan_convert(src_fmt, dst_fmt, lowering);
let _span = tracing::trace_span!(
"image.convert.gl.engine",
?plan,
?lowering,
src_pbo = src.memory() == TensorMemory::Pbo,
)
.entered();
// v1 view()/batch() destination support covers only the single-pass
// PACKED zero-copy path (the glViewport/scissor band set in
// bind_dst). Packed RGB and every planar layout reinterpret the
// destination geometry (`W*3/4 × H`, `H*3` bands), which the band
// lowering does not yet handle, so a view destination declines them
// → CPU fallback. (Band tiling for those is a follow-up.)
if dst.view_origin().is_some()
&& lowering == super::render::DstLowering::ZeroCopy
&& (dst_fmt == PixelFormat::Rgb || dst_fmt.layout() == PixelLayout::Planar)
{
return Err(crate::Error::NotSupported(
"GL view()/batch() destination not yet supported for two-pass packed-RGB / \
planar formats (CPU fallback handles it)"
.into(),
));
}
match plan {
super::render::ConvertPlan::TwoPassPackedRgb => {
return self.convert_to_packed_rgb(
src, src_fmt, dst, dst_fmt, is_int8, rotation, flip, crop,
)
}
super::render::ConvertPlan::TwoPassNvPlanar => {
return self.convert_nv_to_planar_two_pass(
src, src_fmt, dst, dst_fmt, is_int8, rotation, flip, crop,
)
}
super::render::ConvertPlan::SinglePass => {}
}
let target = self.bind_dst(dst, dst_fmt, crop)?;
// Bias the letterbox clear colour for int8 on every lowering: the
// fragment shader XORs rendered pixels and no readback un-biases,
// so the glClear'd letterbox region must be pre-biased.
let crop = Self::int8_bias_clear(is_int8, crop);
let start = Instant::now();
match src.as_pbo() {
Some(src_pbo) => {
// A PBO source uploads via its UNPACK binding — mapping it on
// the GL thread would deadlock on the Pbo message round-trip.
if src_pbo.is_mapped() {
return Err(crate::Error::OpenGl(
"Cannot convert from a mapped PBO tensor".to_string(),
));
}
let src_buffer_id = src_pbo.buffer_id();
self.draw_src_texture_from_pbo(
src,
src_fmt,
src_buffer_id,
dst,
dst_fmt,
is_int8,
rotation,
flip,
crop,
)?;
}
None => {
self.render_packed_or_planar(
src, src_fmt, dst, dst_fmt, is_int8, rotation, flip, crop,
)?;
}
}
log::debug!("engine render ({plan:?}) takes {:?}", start.elapsed());
if let DstTarget::Texture { readback } = target {
// Data is already int8-biased by the shader — readback copies bytes.
let start = Instant::now();
self.readback_rendered(dst, dst_fmt, readback.pbo_id())?;
log::debug!("engine readback takes {:?}", start.elapsed());
}
Ok(())
}
#[allow(clippy::too_many_arguments)]
pub(super) fn draw_decoded_masks_impl(
&mut self,
dst: &mut Tensor<u8>,
dst_fmt: PixelFormat,
detect: &[DetectBox],
segmentation: &[Segmentation],
opacity: f32,
background: Option<(&Tensor<u8>, PixelFormat)>,
color_mode: crate::ColorMode,
) -> Result<(), crate::Error> {
use crate::FunctionTimer;
let _timer = FunctionTimer::new("GLProcessorST::draw_decoded_masks");
if !matches!(
dst_fmt,
PixelFormat::Rgba | PixelFormat::Bgra | PixelFormat::Rgb
) {
return Err(crate::Error::NotSupported(
"Opengl image rendering only supports RGBA, BGRA, or RGB images".to_string(),
));
}
let dst_w = dst.width().ok_or(Error::NotAnImage)?;
let dst_h = dst.height().ok_or(Error::NotAnImage)?;
let memory = dst.memory();
// Trace logs are expensive to format (struct Debug, env reads). Gate
// on the global level filter so they're a single integer compare
// when trace logging is disabled.
if log::log_enabled!(log::Level::Trace) {
log::trace!(
"draw_decoded_masks: dst.memory()={memory:?} {dst_w}x{dst_h} fmt={dst_fmt:?}"
);
}
let pbo_buffer_id = if memory == TensorMemory::Pbo {
match dst.as_pbo() {
Some(p) if !p.is_mapped() => Some(p.buffer_id()),
_ => None,
}
} else {
None
};
let is_dma = match memory {
TensorMemory::Dma => match self.setup_draw_renderbuffer_dma(dst, dst_fmt) {
Ok(()) => {
if log::log_enabled!(log::Level::Trace) {
log::trace!(
"draw_decoded_masks: DMA fast path (setup_draw_renderbuffer_dma OK)"
);
}
true
}
Err(e) => {
warn_slow_path_once("draw_decoded_masks", "setup_draw_renderbuffer_dma", &e);
if let Some(buffer_id) = pbo_buffer_id {
self.setup_renderbuffer_from_pbo(dst, dst_fmt, buffer_id)?;
} else {
self.setup_renderbuffer_non_dma(dst, dst_fmt, ResolvedCrop::no_crop())?;
}
false
}
},
_ if pbo_buffer_id.is_some() => {
if log::log_enabled!(log::Level::Trace) {
log::trace!("draw_decoded_masks: PBO path");
}
self.setup_renderbuffer_from_pbo(dst, dst_fmt, pbo_buffer_id.unwrap())?;
false
}
_ => {
if log::log_enabled!(log::Level::Trace) {
log::trace!("draw_decoded_masks: non-DMA fallback (memory={memory:?})");
}
self.setup_renderbuffer_non_dma(dst, dst_fmt, ResolvedCrop::no_crop())?;
false
}
};
// Write the base layer of the framebuffer *before* running mask
// passes. The framebuffer's backing storage (DMA renderbuffer or
// render_texture) may contain stale pixels from a previous frame
// in a triple-buffered pipeline, so we always actively write it.
//
// - background + DMA: GPU-blit bg → renderbuffer via EGLImage
// (zero-copy).
// - background + non-DMA: upload bg pixels into the render_texture
// that backs the FBO (glTexImage2D). The CPU memcpy is into a
// GL texture, not into the user's DMA buffer, so it's a pure
// upload — not a cache-flushing mapped copy.
// - no background: glClear(0x00000000) on the framebuffer.
if let Some((bg, bg_fmt)) = background {
if bg.width() != Some(dst_w) || bg.height() != Some(dst_h) {
return Err(crate::Error::InvalidShape(
"background dimensions do not match dst".into(),
));
}
if is_dma && bg.memory() == TensorMemory::Dma {
edgefirst_gl::disable(edgefirst_gl::gl::BLEND);
let bg_egl = self.get_or_create_egl_image(CacheKind::Src, bg, bg_fmt)?;
self.draw_camera_texture_eglimage(
bg,
bg_fmt,
bg_egl,
RegionOfInterest {
left: 0.0,
top: 1.0,
right: 1.0,
bottom: 0.0,
},
RegionOfInterest {
left: -1.0,
top: 1.0,
right: 1.0,
bottom: -1.0,
},
0,
crate::Flip::None,
false,
)?;
} else {
// Non-DMA background: upload bg pixels into the
// render_texture attached to the FBO. Writing to dst
// directly would be wrong — the final readback later
// overwrites dst with the framebuffer contents, so we
// have to seed the framebuffer itself.
self.upload_pixels_to_render_texture(bg, bg_fmt, dst_w, dst_h)?;
}
} else {
// No background: actively clear the framebuffer so stale
// pixels from the previous frame do not leak into the output.
unsafe {
edgefirst_gl::gl::ClearColor(0.0, 0.0, 0.0, 0.0);
edgefirst_gl::gl::Clear(edgefirst_gl::gl::COLOR_BUFFER_BIT);
}
}
edgefirst_gl::enable(edgefirst_gl::gl::BLEND);
edgefirst_gl::blend_func_separate(
edgefirst_gl::gl::SRC_ALPHA,
edgefirst_gl::gl::ONE_MINUS_SRC_ALPHA,
edgefirst_gl::gl::ZERO,
edgefirst_gl::gl::ONE,
);
self.set_opacity_uniform(opacity)?;
self.render_box(dst_w, dst_h, detect, color_mode)?;
self.render_segmentation(detect, segmentation, color_mode)?;
edgefirst_gl::finish();
if !is_dma {
let format = match dst_fmt {
PixelFormat::Rgb => edgefirst_gl::gl::RGB,
PixelFormat::Rgba | PixelFormat::Bgra => edgefirst_gl::gl::RGBA,
_ => unreachable!(),
};
if let Some(buffer_id) = pbo_buffer_id {
unsafe {
edgefirst_gl::gl::BindBuffer(edgefirst_gl::gl::PIXEL_PACK_BUFFER, buffer_id);
edgefirst_gl::gl::ReadBuffer(edgefirst_gl::gl::COLOR_ATTACHMENT0);
edgefirst_gl::gl::ReadPixels(
0,
0,
dst_w as i32,
dst_h as i32,
format,
edgefirst_gl::gl::UNSIGNED_BYTE,
std::ptr::null_mut(),
);
edgefirst_gl::gl::BindBuffer(edgefirst_gl::gl::PIXEL_PACK_BUFFER, 0);
edgefirst_gl::gl::Finish();
}
check_gl_error(function!(), line!())?;
if dst_fmt == PixelFormat::Bgra {
let mut dst_map = dst.map_mut()?;
for chunk in dst_map.as_mut_slice().chunks_exact_mut(4) {
chunk.swap(0, 2);
}
}
} else {
let mut dst_map = dst.map_mut()?;
unsafe {
edgefirst_gl::gl::ReadBuffer(edgefirst_gl::gl::COLOR_ATTACHMENT0);
read_pixels_into(
dst_w,
dst_h,
format,
&mut self.readback_scratch,
dst_map.as_mut_slice(),
);
}
check_gl_error(function!(), line!())?;
if dst_fmt == PixelFormat::Bgra {
for chunk in dst_map.as_mut_slice().chunks_exact_mut(4) {
chunk.swap(0, 2);
}
}
}
}
Ok(())
}
#[allow(clippy::too_many_arguments)]
pub(super) fn draw_proto_masks_impl(
&mut self,
dst: &mut Tensor<u8>,
dst_fmt: PixelFormat,
detect: &[DetectBox],
proto_data: &ProtoData,
opacity: f32,
background: Option<(&Tensor<u8>, PixelFormat)>,
color_mode: crate::ColorMode,
) -> crate::Result<()> {
use crate::FunctionTimer;
let _timer = FunctionTimer::new("GLProcessorST::draw_proto_masks");
if !matches!(
dst_fmt,
PixelFormat::Rgba | PixelFormat::Bgra | PixelFormat::Rgb
) {
return Err(crate::Error::NotSupported(
"Opengl image rendering only supports RGBA, BGRA, or RGB images".to_string(),
));
}
let dst_w = dst.width().ok_or(Error::NotAnImage)?;
let dst_h = dst.height().ok_or(Error::NotAnImage)?;
let memory = dst.memory();
if log::log_enabled!(log::Level::Trace) {
log::trace!(
"draw_proto_masks: dst.memory()={memory:?} {dst_w}x{dst_h} fmt={dst_fmt:?}"
);
}
let pbo_buffer_id = if memory == TensorMemory::Pbo {
match dst.as_pbo() {
Some(p) if !p.is_mapped() => Some(p.buffer_id()),
_ => None,
}
} else {
None
};
let is_dma = match memory {
TensorMemory::Dma => match self.setup_draw_renderbuffer_dma(dst, dst_fmt) {
Ok(()) => {
if log::log_enabled!(log::Level::Trace) {
log::trace!(
"draw_proto_masks: DMA fast path (setup_draw_renderbuffer_dma OK)"
);
}
true
}
Err(e) => {
warn_slow_path_once("draw_proto_masks", "setup_draw_renderbuffer_dma", &e);
if let Some(buffer_id) = pbo_buffer_id {
self.setup_renderbuffer_from_pbo(dst, dst_fmt, buffer_id)?;
} else {
self.setup_renderbuffer_non_dma(dst, dst_fmt, ResolvedCrop::no_crop())?;
}
false
}
},
_ if pbo_buffer_id.is_some() => {
if log::log_enabled!(log::Level::Trace) {
log::trace!("draw_proto_masks: PBO path");
}
self.setup_renderbuffer_from_pbo(dst, dst_fmt, pbo_buffer_id.unwrap())?;
false
}
_ => {
if log::log_enabled!(log::Level::Trace) {
log::trace!("draw_proto_masks: non-DMA fallback (memory={memory:?})");
}
self.setup_renderbuffer_non_dma(dst, dst_fmt, ResolvedCrop::no_crop())?;
false
}
};
// Write the base layer of the framebuffer before running mask
// passes. See `draw_decoded_masks_impl` for the rationale — we
// never assume dst is cleared on entry.
if let Some((bg, bg_fmt)) = background {
if bg.width() != Some(dst_w) || bg.height() != Some(dst_h) {
return Err(crate::Error::InvalidShape(
"background dimensions do not match dst".into(),
));
}
if is_dma && bg.memory() == TensorMemory::Dma {
edgefirst_gl::disable(edgefirst_gl::gl::BLEND);
let bg_egl = self.get_or_create_egl_image(CacheKind::Src, bg, bg_fmt)?;
self.draw_camera_texture_eglimage(
bg,
bg_fmt,
bg_egl,
RegionOfInterest {
left: 0.0,
top: 1.0,
right: 1.0,
bottom: 0.0,
},
RegionOfInterest {
left: -1.0,
top: 1.0,
right: 1.0,
bottom: -1.0,
},
0,
crate::Flip::None,
false,
)?;
} else {
self.upload_pixels_to_render_texture(bg, bg_fmt, dst_w, dst_h)?;
}
} else {
unsafe {
edgefirst_gl::gl::ClearColor(0.0, 0.0, 0.0, 0.0);
edgefirst_gl::gl::Clear(edgefirst_gl::gl::COLOR_BUFFER_BIT);
}
}
edgefirst_gl::enable(edgefirst_gl::gl::BLEND);
edgefirst_gl::blend_func_separate(
edgefirst_gl::gl::SRC_ALPHA,
edgefirst_gl::gl::ONE_MINUS_SRC_ALPHA,
edgefirst_gl::gl::ZERO,
edgefirst_gl::gl::ONE,
);
self.set_opacity_uniform(opacity)?;
self.render_box(dst_w, dst_h, detect, color_mode)?;
self.render_proto_segmentation(detect, proto_data, color_mode)?;
edgefirst_gl::finish();
if !is_dma {
let format = match dst_fmt {
PixelFormat::Rgb => edgefirst_gl::gl::RGB,
PixelFormat::Rgba | PixelFormat::Bgra => edgefirst_gl::gl::RGBA,
_ => unreachable!(),
};
if let Some(buffer_id) = pbo_buffer_id {
unsafe {
edgefirst_gl::gl::BindBuffer(edgefirst_gl::gl::PIXEL_PACK_BUFFER, buffer_id);
edgefirst_gl::gl::ReadBuffer(edgefirst_gl::gl::COLOR_ATTACHMENT0);
edgefirst_gl::gl::ReadPixels(
0,
0,
dst_w as i32,
dst_h as i32,
format,
edgefirst_gl::gl::UNSIGNED_BYTE,
std::ptr::null_mut(),
);
edgefirst_gl::gl::BindBuffer(edgefirst_gl::gl::PIXEL_PACK_BUFFER, 0);
edgefirst_gl::gl::Finish();
}
check_gl_error(function!(), line!())?;
if dst_fmt == PixelFormat::Bgra {
let mut dst_map = dst.map_mut()?;
for chunk in dst_map.as_mut_slice().chunks_exact_mut(4) {
chunk.swap(0, 2);
}
}
} else {
let mut dst_map = dst.map_mut()?;
unsafe {
edgefirst_gl::gl::ReadBuffer(edgefirst_gl::gl::COLOR_ATTACHMENT0);
read_pixels_into(
dst_w,
dst_h,
format,
&mut self.readback_scratch,
dst_map.as_mut_slice(),
);
}
check_gl_error(function!(), line!())?;
if dst_fmt == PixelFormat::Bgra {
for chunk in dst_map.as_mut_slice().chunks_exact_mut(4) {
chunk.swap(0, 2);
}
}
}
}
Ok(())
}
pub(super) fn check_src_format_supported(
backend: TransferBackend,
img: &Tensor<u8>,
fmt: PixelFormat,
) -> bool {
if backend.is_zero_copy() && img.memory() == TensorMemory::Dma {
// Zero-copy import path supports:
// Path A (samplerExternalOES): RGBA, GREY, YUYV, NV12
// Path B (R8 texelFetch shader): NV16, NV24 (contiguous only)
// VYUY excluded: Vivante GPU accepts the DRM fourcc but produces
// incorrect output (similarity ~0.28 vs reference).
// NV16/NV24 use Path B — the contiguous-only check is enforced at
// EGLImage creation time in `from_tensor_nv_r8`; multiplane
// sources fall back to CPU via the error path.
matches!(
fmt,
PixelFormat::Rgba
| PixelFormat::Grey
| PixelFormat::Yuyv
| PixelFormat::Nv12
| PixelFormat::Nv16
| PixelFormat::Nv24
)
} else {
// Non-DMA (PBO/Sync): packed RGB(A)/Grey upload via draw_src_texture,
// plus single-plane NV12/NV16/NV24 via the R8-upload ShaderR8 path
// (combined buffer uploaded as R8 + in-shader YUV — no DMA-BUF
// EGLImage needed; the GPU NV path on e.g. orin). Multiplane NV12
// can't be uploaded as one R8 texture and falls to CPU.
matches!(
fmt,
PixelFormat::Rgb | PixelFormat::Rgba | PixelFormat::Grey
) || (matches!(
fmt,
PixelFormat::Nv12 | PixelFormat::Nv16 | PixelFormat::Nv24
) && !img.is_multiplane())
}
}
pub(super) fn check_dst_format_supported(
backend: TransferBackend,
img: &Tensor<u8>,
fmt: PixelFormat,
_is_int8: bool,
has_bgra: bool,
) -> bool {
if fmt == PixelFormat::Bgra && !has_bgra {
return false;
}
if backend.is_zero_copy() && img.memory() == TensorMemory::Dma {
matches!(
fmt,
PixelFormat::Rgba
| PixelFormat::Bgra
| PixelFormat::Grey
| PixelFormat::PlanarRgb
| PixelFormat::Rgb
)
} else {
matches!(
fmt,
PixelFormat::Rgb | PixelFormat::Rgba | PixelFormat::Bgra | PixelFormat::Grey
)
}
}
/// Query GL capabilities and detect GPU vendor/renderer type — see
/// [`GlSupport`]. The two float-color flags report whether the GPU can
/// render to F32 / F16 color attachments (independent extensions: a
/// configuration may have one but not the other), surfaced via
/// `RenderDtypeSupport`.
fn gl_check_support() -> Result<GlSupport, crate::Error> {
if let Ok(version) = edgefirst_gl::get_string(edgefirst_gl::gl::SHADING_LANGUAGE_VERSION) {
log::debug!("GL Shading Language Version: {version:?}");
} else {
log::warn!("Could not get GL Shading Language Version");
}
// Detect GPU vendor / software / virtualized renderers via GL_RENDERER.
let traits = edgefirst_gl::get_string(edgefirst_gl::gl::RENDERER)
.map(|r| {
log::info!("GL_RENDERER: {r}");
classify_renderer(&r)
})
.unwrap_or_default();
let RendererTraits {
vivante: is_vivante,
software: is_software_renderer,
virtual_gpu: is_virtual_gpu,
} = traits;
if is_vivante {
log::warn!(
"Vivante GPU detected — NV12 → planar RGB conversions will use \
two-pass workaround to avoid GPU hang (EDGEAI-1180)"
);
}
if is_software_renderer {
log::warn!(
"Software OpenGL renderer detected — GPU backend will be disabled. \
Image processing will use the CPU backend instead. \
Check EGL ICD configuration if a hardware GPU is expected."
);
}
if is_virtual_gpu {
log::warn!(
"Virtualized GPU detected — concurrent GL across contexts \
mis-renders on paravirtual Metal (observed on macOS CI \
runners); processors will serialize per-message (Full \
policy, same as Vivante). Override with \
EDGEFIRST_GL_SERIALIZE=lifecycle."
);
}
let extensions = unsafe {
let str = edgefirst_gl::gl::GetString(edgefirst_gl::gl::EXTENSIONS);
if str.is_null() {
return Err(crate::Error::GLVersion(
"GL returned no supported extensions".to_string(),
));
}
CStr::from_ptr(str as *const c_char)
.to_string_lossy()
.to_string()
};
log::debug!("GL Extensions: {extensions}");
// The external-OES sampler is required only where the platform's
// import binding uses it (Linux Path A); ANGLE/Metal binds every
// import as TEXTURE_2D and never exposes the extension.
let required_ext: &[&str] = if Platform::EXTERNAL_OES {
&["GL_OES_EGL_image_external_essl3"]
} else {
&[]
};
let extensions = extensions.split_ascii_whitespace().collect::<BTreeSet<_>>();
for required in required_ext {
if !extensions.contains(required) {
return Err(crate::Error::GLVersion(format!(
"GL does not support {required} extension",
)));
}
}
// EDGEFIRST_GL_NO_FLOAT_LINEAR=1 forces the capability off so the
// f32→f16-repack proto fallback (taken only on GPUs lacking the
// extension) is reachable on float-linear-capable lanes — no CI lane
// has such a GPU, so without the override the fallback arm has zero
// coverage anywhere.
let force_no_float_linear = std::env::var("EDGEFIRST_GL_NO_FLOAT_LINEAR")
.map(|v| v == "1")
.unwrap_or(false);
let has_float_linear =
extensions.contains("GL_OES_texture_float_linear") && !force_no_float_linear;
if force_no_float_linear {
log::info!("GL_OES_texture_float_linear forced OFF via EDGEFIRST_GL_NO_FLOAT_LINEAR");
}
log::debug!("GL_OES_texture_float_linear: {has_float_linear}");
let has_bgra = extensions.contains("GL_EXT_texture_format_BGRA8888");
log::debug!("GL_EXT_texture_format_BGRA8888: {has_bgra}");
// Float-color-buffer extensions gate F32/F16 destinations on the
// IOSurface render path. The two extensions are independent: a
// configuration may expose one but not the other, so consumers
// (e.g. profiler/ORT CoreML path) probe each separately and pick
// the preferred dtype.
let supports_f32_color = extensions.contains("GL_EXT_color_buffer_float");
let supports_f16_color = extensions.contains("GL_EXT_color_buffer_half_float");
log::debug!("GL_EXT_color_buffer_float: {supports_f32_color}");
log::debug!("GL_EXT_color_buffer_half_float: {supports_f16_color}");
Ok(GlSupport {
has_float_linear,
has_bgra,
renderer: traits,
supports_f32_color,
supports_f16_color,
})
}
/// Invalidate EGL binding state on all destination textures.
/// Called when the dst EGLImage cache evicts or sweeps entries.
fn invalidate_dst_textures(&mut self) {
self.render_texture.invalidate_egl_binding();
self.draw_render_texture.invalidate_egl_binding();
}
/// Invalidate EGL binding state on all source textures.
/// Called when the src EGLImage cache evicts or sweeps entries.
fn invalidate_src_textures(&mut self) {
self.camera_eglimage_texture.invalidate_egl_binding();
self.nv_r8_texture.invalidate_egl_binding();
self.camera_normal_texture.invalidate_egl_binding();
}
/// Classify and bind the destination render target — the single entry
/// point absorbing the per-memory `setup_renderbuffer_*` fan-out. The
/// pure classification lives in [`super::render::lower_dst`]; this
/// performs the GL work and tells the caller what completes the convert.
fn bind_dst(
&mut self,
dst: &Tensor<u8>,
dst_fmt: PixelFormat,
crop: ResolvedCrop,
) -> crate::Result<DstTarget> {
match super::render::lower_dst(
self.gl_context.transfer_backend.is_zero_copy(),
dst.memory(),
) {
super::render::DstLowering::ZeroCopy => {
self.setup_renderbuffer_dma(dst, dst_fmt)?;
Ok(DstTarget::ZeroCopyImage)
}
super::render::DstLowering::TexturePbo => {
let dst_pbo = dst.as_pbo().ok_or_else(|| {
crate::Error::OpenGl(
"bind_dst: PBO-lowered destination is not a PBO tensor".to_string(),
)
})?;
if dst_pbo.is_mapped() {
return Err(crate::Error::OpenGl(
"Cannot convert to a mapped PBO tensor".to_string(),
));
}
let id = dst_pbo.buffer_id();
self.setup_renderbuffer_from_pbo(dst, dst_fmt, id)?;
Ok(DstTarget::Texture {
readback: DstReadback::Pbo(id),
})
}
super::render::DstLowering::TextureMem => {
self.setup_renderbuffer_non_dma(dst, dst_fmt, crop)?;
Ok(DstTarget::Texture {
readback: DstReadback::Mem,
})
}
}
}
fn setup_renderbuffer_dma(
&mut self,
dst: &Tensor<u8>,
dst_fmt: PixelFormat,
) -> crate::Result<()> {
self.convert_fbo.bind();
let dst_w = dst.width().ok_or(Error::NotAnImage)?;
let dst_h = dst.height().ok_or(Error::NotAnImage)?;
let (width, height) = if dst_fmt == PixelFormat::PlanarRgb {
(dst_w as i32, (dst_h * 3) as i32)
} else {
(dst_w as i32, dst_h as i32)
};
let dst_key = BufferImportKey::from_tensor(dst, dst_fmt, true);
let luma_id = dst_key.luma_id;
let dest_egl = self.get_or_create_egl_image(CacheKind::Dst, dst, dst_fmt)?;
match self.cached_dst_renderbuffer(dst, dst_fmt) {
Some(rbo) => unsafe {
edgefirst_gl::gl::BindRenderbuffer(edgefirst_gl::gl::RENDERBUFFER, rbo);
edgefirst_gl::gl::FramebufferRenderbuffer(
edgefirst_gl::gl::FRAMEBUFFER,
edgefirst_gl::gl::COLOR_ATTACHMENT0,
edgefirst_gl::gl::RENDERBUFFER,
rbo,
);
check_gl_error(function!(), line!())?;
},
None => unsafe {
if let Some(p) = &self.texture_program_yuv {
edgefirst_gl::gl::UseProgram(p.id);
}
edgefirst_gl::gl::ActiveTexture(edgefirst_gl::gl::TEXTURE0);
edgefirst_gl::gl::BindTexture(edgefirst_gl::gl::TEXTURE_2D, self.render_texture.id);
super::core::set_tex_filter(edgefirst_gl::gl::TEXTURE_2D, edgefirst_gl::gl::LINEAR);
if self
.render_texture
.bind_egl_image(&self.gl_context, dst_key, dest_egl)?
{
edgefirst_gl::gl::FramebufferTexture2D(
edgefirst_gl::gl::FRAMEBUFFER,
edgefirst_gl::gl::COLOR_ATTACHMENT0,
edgefirst_gl::gl::TEXTURE_2D,
self.render_texture.id,
0,
);
log::trace!("setup_renderbuffer_dma: bound new dst EGLImage id={luma_id:#x}");
} else {
log::trace!(
"setup_renderbuffer_dma: reusing bound dst EGLImage id={luma_id:#x}"
);
}
check_gl_error(function!(), line!())?;
},
}
// A view()/batch() destination imported the whole PARENT above (cache key
// + `DmaImportAttrs` both pivot on `view_origin`); render this tile into
// its band via `glViewport`. A whole tensor fills its full surface. The
// matching `glScissor` (so the letterbox clear cannot wipe sibling tiles)
// is set in `convert_to`, which owns the clear — both lower the band
// through `region_to_viewport_top_down`, the single home for the
// verified top-down orientation of the dst DMA EGLImage.
let vp = match dst.view_origin() {
Some(vo) => super::render::region_to_viewport_top_down(crate::Region::new(
vo.x, vo.y, dst_w, dst_h,
)),
None => super::render::Viewport {
x: 0,
y: 0,
w: width,
h: height,
},
};
unsafe {
edgefirst_gl::gl::Viewport(vp.x, vp.y, vp.w, vp.h);
}
Ok(())
}
/// Variant of [`setup_renderbuffer_dma`] used exclusively by draw operations
/// (`draw_decoded_masks`, `draw_proto_masks`).
///
/// Uses a dedicated FBO (`draw_fbo`) and texture (`draw_render_texture`) so
/// that `EGLImageTargetTexture2DOES` calls made during convert do not
/// invalidate the draw path's cached binding, and vice versa. On Vivante
/// GC7000UL (texture path, `use_renderbuffer = false`) each
/// `EGLImageTargetTexture2DOES` call costs ~4–11 ms, so eliminating the
/// cross-path invalidation removes two redundant calls per frame when both
/// convert and draw are active.
fn setup_draw_renderbuffer_dma(
&mut self,
dst: &Tensor<u8>,
dst_fmt: PixelFormat,
) -> crate::Result<()> {
self.draw_fbo.bind();
let dst_w = dst.width().ok_or(Error::NotAnImage)?;
let dst_h = dst.height().ok_or(Error::NotAnImage)?;
let (width, height) = if dst_fmt == PixelFormat::PlanarRgb {
(dst_w as i32, (dst_h * 3) as i32)
} else {
(dst_w as i32, dst_h as i32)
};
let dst_key = BufferImportKey::from_tensor(dst, dst_fmt, true);
let luma_id = dst_key.luma_id;
let dest_egl = self.get_or_create_egl_image(CacheKind::Dst, dst, dst_fmt)?;
match self.cached_dst_renderbuffer(dst, dst_fmt) {
Some(rbo) => unsafe {
edgefirst_gl::gl::BindRenderbuffer(edgefirst_gl::gl::RENDERBUFFER, rbo);
edgefirst_gl::gl::FramebufferRenderbuffer(
edgefirst_gl::gl::FRAMEBUFFER,
edgefirst_gl::gl::COLOR_ATTACHMENT0,
edgefirst_gl::gl::RENDERBUFFER,
rbo,
);
check_gl_error(function!(), line!())?;
},
None => unsafe {
edgefirst_gl::gl::ActiveTexture(edgefirst_gl::gl::TEXTURE0);
edgefirst_gl::gl::BindTexture(
edgefirst_gl::gl::TEXTURE_2D,
self.draw_render_texture.id,
);
super::core::set_tex_filter(edgefirst_gl::gl::TEXTURE_2D, edgefirst_gl::gl::LINEAR);
if self
.draw_render_texture
.bind_egl_image(&self.gl_context, dst_key, dest_egl)?
{
edgefirst_gl::gl::FramebufferTexture2D(
edgefirst_gl::gl::FRAMEBUFFER,
edgefirst_gl::gl::COLOR_ATTACHMENT0,
edgefirst_gl::gl::TEXTURE_2D,
self.draw_render_texture.id,
0,
);
log::trace!(
"setup_draw_renderbuffer_dma: bound new dst EGLImage id={luma_id:#x}"
);
} else {
log::trace!(
"setup_draw_renderbuffer_dma: reusing bound dst EGLImage id={luma_id:#x}"
);
}
check_gl_error(function!(), line!())?;
},
}
unsafe {
edgefirst_gl::gl::Viewport(0, 0, width, height);
}
Ok(())
}
/// Bias a letterbox clear colour by XOR 0x80 for int8 destinations, since
/// `glClear` bypasses the shader that otherwise applies the bias. No-op when
/// not int8 or when there is no fill colour. Shared by every destination path.
fn int8_bias_clear(is_int8: bool, mut crop: ResolvedCrop) -> ResolvedCrop {
if is_int8 {
if let Some(ref mut color) = crop.dst_color {
color[0] ^= 0x80;
color[1] ^= 0x80;
color[2] ^= 0x80;
}
}
crop
}
/// Render `src` into the already-bound destination FBO as `dst_fmt`,
/// dispatching packed vs planar; the draws select their int8 program
/// variants from `is_int8` at draw time. This is the converged per-tile
/// draw shared by the texture and DMA destination paths — they differ
/// only in FBO setup and readback, never in this draw.
#[allow(clippy::too_many_arguments)]
fn render_packed_or_planar(
&mut self,
src: &Tensor<u8>,
src_fmt: PixelFormat,
dst: &mut Tensor<u8>,
dst_fmt: PixelFormat,
is_int8: bool,
rotation: crate::Rotation,
flip: Flip,
crop: ResolvedCrop,
) -> crate::Result<()> {
if dst_fmt.layout() == PixelLayout::Planar {
self.convert_to_planar(src, src_fmt, dst, dst_fmt, is_int8, rotation, flip, crop)
} else {
self.convert_to(src, src_fmt, dst, dst_fmt, is_int8, rotation, flip, crop)
}
}
/// Read the rendered FBO colour attachment (`COLOR_ATTACHMENT0`) into the
/// destination, applying the BGRA byte-swap when `dst_fmt` is BGRA. `pbo_id`
/// selects the target: `None` reads straight into the mapped Mem tensor (the
/// preceding draw has already finished the GPU); `Some(id)` reads into the
/// bound PBO PACK buffer and issues a finishing flush so the async transfer
/// completes. The converged readback shared by the non-DMA and any-to-PBO
/// paths — they differ only in this target selector.
fn readback_rendered(
&mut self,
dst: &mut Tensor<u8>,
dst_fmt: PixelFormat,
pbo_id: Option<u32>,
) -> crate::Result<()> {
let dst_w = dst.width().ok_or(Error::NotAnImage)?;
let dst_h = dst.height().ok_or(Error::NotAnImage)?;
let dest_format = match dst_fmt {
PixelFormat::Rgb => edgefirst_gl::gl::RGB,
PixelFormat::Rgba | PixelFormat::Bgra => edgefirst_gl::gl::RGBA,
PixelFormat::Grey => edgefirst_gl::gl::RED,
_ => {
return Err(crate::Error::NotSupported(format!(
"GL readback not supported for {dst_fmt}"
)))
}
};
let len = dst.len();
match pbo_id {
None => unsafe {
let mut dst_map = dst.map_mut()?;
edgefirst_gl::gl::ReadBuffer(edgefirst_gl::gl::COLOR_ATTACHMENT0);
read_pixels_into(
dst_w,
dst_h,
dest_format,
&mut self.readback_scratch,
dst_map.as_mut_slice(),
);
if dst_fmt == PixelFormat::Bgra {
for chunk in dst_map.as_mut_slice().chunks_exact_mut(4) {
chunk.swap(0, 2);
}
}
},
Some(buffer_id) => {
unsafe {
edgefirst_gl::gl::BindBuffer(edgefirst_gl::gl::PIXEL_PACK_BUFFER, buffer_id);
edgefirst_gl::gl::ReadBuffer(edgefirst_gl::gl::COLOR_ATTACHMENT0);
edgefirst_gl::gl::ReadPixels(
0,
0,
dst_w as i32,
dst_h as i32,
dest_format,
edgefirst_gl::gl::UNSIGNED_BYTE,
std::ptr::null_mut(),
);
edgefirst_gl::gl::BindBuffer(edgefirst_gl::gl::PIXEL_PACK_BUFFER, 0);
edgefirst_gl::gl::Finish();
}
// BGRA R↔B swap must map the PBO on the GL thread. Int8 XOR 0x80
// is handled in the fragment shader — no CPU map needed.
if dst_fmt == PixelFormat::Bgra {
unsafe {
edgefirst_gl::gl::BindBuffer(
edgefirst_gl::gl::PIXEL_PACK_BUFFER,
buffer_id,
);
let ptr = edgefirst_gl::gl::MapBufferRange(
edgefirst_gl::gl::PIXEL_PACK_BUFFER,
0,
len as isize,
edgefirst_gl::gl::MAP_READ_BIT | edgefirst_gl::gl::MAP_WRITE_BIT,
);
if ptr.is_null() {
edgefirst_gl::gl::BindBuffer(edgefirst_gl::gl::PIXEL_PACK_BUFFER, 0);
return Err(crate::Error::OpenGl(
"glMapBufferRange returned null for BGRA byte-swap".to_string(),
));
}
let slice = std::slice::from_raw_parts_mut(ptr as *mut u8, len);
for chunk in slice.chunks_exact_mut(4) {
chunk.swap(0, 2);
}
edgefirst_gl::gl::UnmapBuffer(edgefirst_gl::gl::PIXEL_PACK_BUFFER);
edgefirst_gl::gl::BindBuffer(edgefirst_gl::gl::PIXEL_PACK_BUFFER, 0);
}
}
}
}
check_gl_error(function!(), line!())?;
Ok(())
}
fn setup_renderbuffer_non_dma(
&mut self,
dst: &Tensor<u8>,
dst_fmt: PixelFormat,
crop: ResolvedCrop,
) -> crate::Result<()> {
let dst_w = dst.width().ok_or(Error::NotAnImage)?;
let dst_h = dst.height().ok_or(Error::NotAnImage)?;
let is_planar = dst_fmt.layout() == PixelLayout::Planar;
let (width, height) = if is_planar {
let width = dst_w / 4;
let height = match dst_fmt.channels() {
4 => dst_h * 4,
3 => dst_h * 3,
1 => dst_h,
_ => unreachable!(),
};
(width as i32, height as i32)
} else {
(dst_w as i32, dst_h as i32)
};
// BGRA textures as framebuffer color attachments have GPU-dependent
// swizzle behavior: some implementations don't swizzle fragment shader
// output, causing R↔B channel swap. Work around this by using RGBA
// format internally — BGRA pixel data is byte-swapped (R↔B) before
// upload, and the readback path swaps back.
let is_bgra = !is_planar && dst_fmt == PixelFormat::Bgra;
if is_bgra && !self.bgra_warned {
log::warn!(
"BGRA destination: using RGBA internal format with CPU R↔B byte-swap workaround"
);
self.bgra_warned = true;
}
let format = if is_planar {
edgefirst_gl::gl::RED
} else {
match dst_fmt {
PixelFormat::Rgb => edgefirst_gl::gl::RGB,
PixelFormat::Rgba | PixelFormat::Bgra => edgefirst_gl::gl::RGBA, // BGRA uses RGBA internally
PixelFormat::Grey => edgefirst_gl::gl::RED,
_ => unreachable!(),
}
};
let start = Instant::now();
self.convert_fbo.bind();
let map;
let mut swapped_buf;
let pixels = if crop.dst_rect.is_none_or(|crop| {
crop.top == 0 && crop.left == 0 && crop.height == dst_h && crop.width == dst_w
}) {
std::ptr::null()
} else {
map = dst.map_read()?;
if is_bgra {
// Swap R↔B to convert BGRA→RGBA for the RGBA texture.
swapped_buf = map.as_slice().to_vec();
for chunk in swapped_buf.chunks_exact_mut(4) {
chunk.swap(0, 2);
}
swapped_buf.as_ptr() as *const c_void
} else {
map.as_ptr() as *const c_void
}
};
unsafe {
edgefirst_gl::gl::UseProgram(self.texture_program.id);
edgefirst_gl::gl::ActiveTexture(edgefirst_gl::gl::TEXTURE0);
edgefirst_gl::gl::BindTexture(edgefirst_gl::gl::TEXTURE_2D, self.render_texture.id);
super::core::set_tex_filter(edgefirst_gl::gl::TEXTURE_2D, edgefirst_gl::gl::LINEAR);
edgefirst_gl::gl::TexImage2D(
edgefirst_gl::gl::TEXTURE_2D,
0,
format as i32,
width,
height,
0,
format,
edgefirst_gl::gl::UNSIGNED_BYTE,
pixels,
);
// TexImage2D overwrites any EGLImage binding on this texture.
self.render_texture.invalidate_egl_binding();
check_gl_error(function!(), line!())?;
edgefirst_gl::gl::FramebufferTexture2D(
edgefirst_gl::gl::FRAMEBUFFER,
edgefirst_gl::gl::COLOR_ATTACHMENT0,
edgefirst_gl::gl::TEXTURE_2D,
self.render_texture.id,
0,
);
check_gl_error(function!(), line!())?;
edgefirst_gl::gl::Viewport(0, 0, width, height);
}
log::debug!("Set up framebuffer takes {:?}", start.elapsed());
Ok(())
}
/// Set up a framebuffer for overlay rendering on a PBO-backed destination.
///
/// Binds the PBO as `GL_PIXEL_UNPACK_BUFFER` and uploads its contents to
/// the render texture via `TexImage2D` with a NULL pointer — GL reads
/// directly from PBO memory without any CPU-side `map()` call. This avoids
/// the deadlock that occurs when `setup_renderbuffer_non_dma` tries to
/// `tensor.map()` a PBO on the GL thread.
/// Upload CPU-side pixel data into `self.render_texture` which is
/// attached as the FBO color attachment. Used for the non-DMA
/// background path in `draw_decoded_masks_impl` /
/// `draw_proto_masks_impl`: the source buffer is a user-provided
/// tensor in plain memory, so we do a single CPU→GPU upload into the
/// texture rather than memcpying into the caller's dst (which the
/// final framebuffer readback would overwrite anyway).
///
/// If the source is BGRA we byte-swap into a scratch buffer so the
/// RGBA-internal render target holds the correct pixels after the
/// later readback-time R↔B swap.
fn upload_pixels_to_render_texture(
&mut self,
src: &Tensor<u8>,
src_fmt: PixelFormat,
dst_w: usize,
dst_h: usize,
) -> crate::Result<()> {
use edgefirst_tensor::TensorMapTrait;
let map = src.map_read()?;
let src_slice = map.as_slice();
let format = match src_fmt {
PixelFormat::Rgb => edgefirst_gl::gl::RGB,
PixelFormat::Rgba | PixelFormat::Bgra => edgefirst_gl::gl::RGBA,
_ => {
return Err(crate::Error::NotSupported(format!(
"non-DMA bg upload not supported for {src_fmt}",
)))
}
};
let swapped: Option<Vec<u8>> = if src_fmt == PixelFormat::Bgra {
let mut v = src_slice.to_vec();
for chunk in v.chunks_exact_mut(4) {
chunk.swap(0, 2);
}
Some(v)
} else {
None
};
let pixels = swapped.as_deref().unwrap_or(src_slice).as_ptr() as *const c_void;
unsafe {
edgefirst_gl::gl::BindTexture(edgefirst_gl::gl::TEXTURE_2D, self.render_texture.id);
edgefirst_gl::gl::TexImage2D(
edgefirst_gl::gl::TEXTURE_2D,
0,
format as i32,
dst_w as i32,
dst_h as i32,
0,
format,
edgefirst_gl::gl::UNSIGNED_BYTE,
pixels,
);
// TexImage2D invalidates any prior EGLImage binding.
self.render_texture.invalidate_egl_binding();
check_gl_error(function!(), line!())?;
edgefirst_gl::gl::FramebufferTexture2D(
edgefirst_gl::gl::FRAMEBUFFER,
edgefirst_gl::gl::COLOR_ATTACHMENT0,
edgefirst_gl::gl::TEXTURE_2D,
self.render_texture.id,
0,
);
check_gl_error(function!(), line!())?;
}
Ok(())
}
/// Low-level PBO render-target setup with explicit GL format and type.
///
/// Binds `buffer_id` as `GL_PIXEL_UNPACK_BUFFER`, calls `TexImage2D` with
/// the provided `internal_format`, `client_format`, and `gl_type`, then
/// attaches the texture to the FBO color attachment and sets the viewport.
///
/// The `(width, height)` are the logical pixel dimensions of the render
/// target (caller is responsible for planar-packing remapping if needed).
///
/// # Safety (caller responsibility)
/// `internal_format`, `client_format`, and `gl_type` must form a valid
/// `TexImage2D` combination for the bound GLES context.
fn setup_renderbuffer_from_pbo_inner(
&mut self,
width: i32,
height: i32,
buffer_id: u32,
internal_format: u32,
client_format: u32,
gl_type: u32,
) -> crate::Result<()> {
self.convert_fbo.bind();
unsafe {
edgefirst_gl::gl::UseProgram(self.texture_program.id);
edgefirst_gl::gl::ActiveTexture(edgefirst_gl::gl::TEXTURE0);
edgefirst_gl::gl::BindTexture(edgefirst_gl::gl::TEXTURE_2D, self.render_texture.id);
super::core::set_tex_filter(edgefirst_gl::gl::TEXTURE_2D, edgefirst_gl::gl::LINEAR);
// Upload existing PBO content to the render texture.
// Binding PBO as UNPACK buffer makes TexImage2D read from it.
edgefirst_gl::gl::BindBuffer(edgefirst_gl::gl::PIXEL_UNPACK_BUFFER, buffer_id);
edgefirst_gl::gl::TexImage2D(
edgefirst_gl::gl::TEXTURE_2D,
0,
internal_format as i32,
width,
height,
0,
client_format,
gl_type,
std::ptr::null(),
);
edgefirst_gl::gl::BindBuffer(edgefirst_gl::gl::PIXEL_UNPACK_BUFFER, 0);
// TexImage2D overwrites any EGLImage binding on this texture.
self.render_texture.invalidate_egl_binding();
check_gl_error(function!(), line!())?;
edgefirst_gl::gl::FramebufferTexture2D(
edgefirst_gl::gl::FRAMEBUFFER,
edgefirst_gl::gl::COLOR_ATTACHMENT0,
edgefirst_gl::gl::TEXTURE_2D,
self.render_texture.id,
0,
);
check_gl_error(function!(), line!())?;
edgefirst_gl::gl::Viewport(0, 0, width, height);
}
Ok(())
}
/// Set up a u8 (UNSIGNED_BYTE) PBO render target for the given format.
///
/// Computes the correct GL `format` from `dst_fmt` (handling planar
/// packing layout) and delegates to [`setup_renderbuffer_from_pbo_inner`]
/// with `UNSIGNED_BYTE` as the GL type. The next task adds an analogous
/// float variant that calls the inner helper with `R32F`/`RGBA16F` and
/// `FLOAT`/`HALF_FLOAT` respectively.
fn setup_renderbuffer_from_pbo(
&mut self,
dst: &Tensor<u8>,
dst_fmt: PixelFormat,
buffer_id: u32,
) -> crate::Result<()> {
let dst_w = dst.width().ok_or(Error::NotAnImage)?;
let dst_h = dst.height().ok_or(Error::NotAnImage)?;
let is_planar = dst_fmt.layout() == PixelLayout::Planar;
let (width, height) = if is_planar {
let width = dst_w / 4;
let height = match dst_fmt.channels() {
4 => dst_h * 4,
3 => dst_h * 3,
1 => dst_h,
_ => unreachable!(),
};
(width as i32, height as i32)
} else {
(dst_w as i32, dst_h as i32)
};
let format = if is_planar {
edgefirst_gl::gl::RED
} else {
match dst_fmt {
PixelFormat::Rgb => edgefirst_gl::gl::RGB,
PixelFormat::Rgba | PixelFormat::Bgra => edgefirst_gl::gl::RGBA,
PixelFormat::Grey => edgefirst_gl::gl::RED,
_ => {
return Err(crate::Error::NotSupported(format!(
"PBO renderbuffer not supported for {dst_fmt}",
)))
}
}
};
self.setup_renderbuffer_from_pbo_inner(
width,
height,
buffer_id,
format,
format,
edgefirst_gl::gl::UNSIGNED_BYTE,
)
}
/// Upload source image from a PBO and render to the current framebuffer.
/// This is the PBO equivalent of draw_src_texture — instead of mapping
/// the tensor to CPU and calling glTexImage2D with a data pointer, we
/// bind the source PBO as GL_PIXEL_UNPACK_BUFFER and pass NULL, causing
/// GL to read directly from the PBO (zero CPU copy).
#[allow(clippy::too_many_arguments)]
fn draw_src_texture_from_pbo(
&mut self,
src: &Tensor<u8>,
src_fmt: PixelFormat,
src_buffer_id: u32,
dst: &Tensor<u8>,
_dst_fmt: PixelFormat,
is_int8: bool,
rotation: crate::Rotation,
flip: Flip,
crop: ResolvedCrop,
) -> Result<(), Error> {
let src_w = src.width().ok_or(Error::NotAnImage)?;
let src_h = src.height().ok_or(Error::NotAnImage)?;
let dst_w = dst.width().ok_or(Error::NotAnImage)?;
let dst_h = dst.height().ok_or(Error::NotAnImage)?;
let texture_target = edgefirst_gl::gl::TEXTURE_2D;
let texture_format = match src_fmt {
PixelFormat::Rgb => edgefirst_gl::gl::RGB,
PixelFormat::Rgba => edgefirst_gl::gl::RGBA,
PixelFormat::Grey => edgefirst_gl::gl::RED,
_ => {
return Err(Error::NotSupported(format!(
"PBO upload not supported for {src_fmt:?}",
)));
}
};
self.convert_stats.src_pbo_uploads += 1;
tracing::Span::current().record("src_feed", "pbo");
let has_crop = crop
.dst_rect
.is_some_and(|x| x.left != 0 || x.top != 0 || x.width != dst_w || x.height != dst_h);
let src_roi = if let Some(crop) = crop.src_rect {
RegionOfInterest::from_crop_clamped(&crop, src_w, src_h)
} else {
RegionOfInterest {
left: 0.,
top: 1.,
right: 1.,
bottom: 0.,
}
};
let cvt_screen_coord = |normalized| normalized * 2.0 - 1.0;
let mut dst_roi = if let Some(crop) = crop.dst_rect {
RegionOfInterest {
left: cvt_screen_coord(crop.left as f32 / dst_w as f32),
top: cvt_screen_coord((crop.top + crop.height) as f32 / dst_h as f32),
right: cvt_screen_coord((crop.left + crop.width) as f32 / dst_w as f32),
bottom: cvt_screen_coord(crop.top as f32 / dst_h as f32),
}
} else {
RegionOfInterest {
left: -1.,
top: 1.,
right: 1.,
bottom: -1.,
}
};
let rotation_offset = match rotation {
crate::Rotation::None => 0,
crate::Rotation::Clockwise90 => 1,
crate::Rotation::Rotate180 => 2,
crate::Rotation::CounterClockwise90 => 3,
};
unsafe {
if has_crop {
if let Some(dst_color) = crop.dst_color {
edgefirst_gl::gl::ClearColor(
dst_color[0] as f32 / 255.0,
dst_color[1] as f32 / 255.0,
dst_color[2] as f32 / 255.0,
dst_color[3] as f32 / 255.0,
);
edgefirst_gl::gl::Clear(edgefirst_gl::gl::COLOR_BUFFER_BIT);
}
}
// Draw-time program selection (see draw_src_texture).
edgefirst_gl::gl::UseProgram(if is_int8 {
self.texture_int8_program.id
} else {
self.texture_program.id
});
edgefirst_gl::gl::ActiveTexture(edgefirst_gl::gl::TEXTURE0);
edgefirst_gl::gl::BindTexture(texture_target, self.camera_normal_texture.id);
super::core::set_tex_filter_clamp(texture_target, edgefirst_gl::gl::LINEAR);
if src_fmt == PixelFormat::Grey {
for swizzle in [
edgefirst_gl::gl::TEXTURE_SWIZZLE_R,
edgefirst_gl::gl::TEXTURE_SWIZZLE_G,
edgefirst_gl::gl::TEXTURE_SWIZZLE_B,
] {
edgefirst_gl::gl::TexParameteri(
edgefirst_gl::gl::TEXTURE_2D,
swizzle,
edgefirst_gl::gl::RED as i32,
);
}
} else {
for (swizzle, src_component) in [
(edgefirst_gl::gl::TEXTURE_SWIZZLE_R, edgefirst_gl::gl::RED),
(edgefirst_gl::gl::TEXTURE_SWIZZLE_G, edgefirst_gl::gl::GREEN),
(edgefirst_gl::gl::TEXTURE_SWIZZLE_B, edgefirst_gl::gl::BLUE),
] {
edgefirst_gl::gl::TexParameteri(
edgefirst_gl::gl::TEXTURE_2D,
swizzle,
src_component as i32,
);
}
}
// Honour a padded source row stride: a PBO written by the CPU JPEG
// decoder (or any producer) may have 64-byte-aligned rows, so the
// bytes between logical rows must be skipped on upload. Mirror the
// non-PBO `draw_src_texture` path (GL_UNPACK_ROW_LENGTH in pixels);
// 0 means "tightly packed = src_w". Without this a padded PBO source
// shears on every row after the first.
let src_bpp = src_fmt.channels();
let row_len_px = src
.effective_row_stride()
.map(|s| s / src_bpp)
.filter(|&px| px != src_w)
.unwrap_or(0);
// Bind source PBO as UNPACK buffer — glTexImage2D reads from it
edgefirst_gl::gl::BindBuffer(edgefirst_gl::gl::PIXEL_UNPACK_BUFFER, src_buffer_id);
edgefirst_gl::gl::PixelStorei(edgefirst_gl::gl::UNPACK_ROW_LENGTH, row_len_px as i32);
edgefirst_gl::gl::TexImage2D(
texture_target,
0,
texture_format as i32,
src_w as i32,
src_h as i32,
0,
texture_format,
edgefirst_gl::gl::UNSIGNED_BYTE,
std::ptr::null(), // NULL = read from bound UNPACK buffer
);
edgefirst_gl::gl::PixelStorei(edgefirst_gl::gl::UNPACK_ROW_LENGTH, 0);
edgefirst_gl::gl::BindBuffer(edgefirst_gl::gl::PIXEL_UNPACK_BUFFER, 0);
// Force texture cache state to be rebuilt next call
self.camera_normal_texture.width = 0;
edgefirst_gl::gl::BindBuffer(edgefirst_gl::gl::ARRAY_BUFFER, self.vertex_buffer.id);
edgefirst_gl::gl::EnableVertexAttribArray(self.vertex_buffer.buffer_index);
match flip {
crate::Flip::None => {}
crate::Flip::Vertical => {
std::mem::swap(&mut dst_roi.top, &mut dst_roi.bottom);
}
crate::Flip::Horizontal => {
std::mem::swap(&mut dst_roi.left, &mut dst_roi.right);
}
}
let camera_vertices: [f32; 12] = [
dst_roi.left,
dst_roi.top,
0., // left top
dst_roi.right,
dst_roi.top,
0., // right top
dst_roi.right,
dst_roi.bottom,
0., // right bottom
dst_roi.left,
dst_roi.bottom,
0., // left bottom
];
edgefirst_gl::gl::BufferData(
edgefirst_gl::gl::ARRAY_BUFFER,
(camera_vertices.len() * std::mem::size_of::<f32>()) as isize,
camera_vertices.as_ptr() as *const c_void,
edgefirst_gl::gl::STATIC_DRAW,
);
edgefirst_gl::gl::VertexAttribPointer(
self.vertex_buffer.buffer_index,
3,
edgefirst_gl::gl::FLOAT,
edgefirst_gl::gl::FALSE,
0,
std::ptr::null(),
);
let texture_coords: [[f32; 8]; 4] = [
[
src_roi.left,
src_roi.top,
src_roi.right,
src_roi.top,
src_roi.right,
src_roi.bottom,
src_roi.left,
src_roi.bottom,
],
[
src_roi.left,
src_roi.bottom,
src_roi.left,
src_roi.top,
src_roi.right,
src_roi.top,
src_roi.right,
src_roi.bottom,
],
[
src_roi.right,
src_roi.bottom,
src_roi.left,
src_roi.bottom,
src_roi.left,
src_roi.top,
src_roi.right,
src_roi.top,
],
[
src_roi.right,
src_roi.top,
src_roi.right,
src_roi.bottom,
src_roi.left,
src_roi.bottom,
src_roi.left,
src_roi.top,
],
];
edgefirst_gl::gl::BindBuffer(edgefirst_gl::gl::ARRAY_BUFFER, self.texture_buffer.id);
edgefirst_gl::gl::EnableVertexAttribArray(self.texture_buffer.buffer_index);
edgefirst_gl::gl::BufferData(
edgefirst_gl::gl::ARRAY_BUFFER,
(texture_coords[0].len() * std::mem::size_of::<f32>()) as isize,
texture_coords[rotation_offset].as_ptr() as *const c_void,
edgefirst_gl::gl::STATIC_DRAW,
);
edgefirst_gl::gl::VertexAttribPointer(
self.texture_buffer.buffer_index,
2,
edgefirst_gl::gl::FLOAT,
edgefirst_gl::gl::FALSE,
0,
std::ptr::null(),
);
edgefirst_gl::gl::DrawArrays(edgefirst_gl::gl::TRIANGLE_FAN, 0, 4);
edgefirst_gl::gl::DisableVertexAttribArray(self.vertex_buffer.buffer_index);
edgefirst_gl::gl::DisableVertexAttribArray(self.texture_buffer.buffer_index);
edgefirst_gl::gl::Finish();
}
check_gl_error(function!(), line!())?;
Ok(())
}
/// Pick the NV* GPU conversion path for `src`/`src_fmt`, honoring the
/// `EDGEFIRST_NV_CONVERT_PATH` preference. Returns the path to *attempt*;
/// the caller maps an EGLImage-creation error to the [`NvConvertPath::Cpu`]
/// fallback. Forcing an unavailable path logs a warning and falls back to
/// the only viable one rather than failing.
///
/// Capability:
/// - [`NvConvertPath::ShaderR8`] needs a single combined-plane buffer, so it
/// covers single-plane NV12/NV16/NV24 but NOT true-multiplane NV12.
/// - [`NvConvertPath::ExternalSampler`] (samplerExternalOES) is wired for
/// NV12 only (incl. multiplane); NV16/NV24 have no sampler path.
///
/// `render_fmt` is the format of the render target this draw writes
/// (Rgb/PlanarRgb arrive here only as the LOGICAL format of a two-pass
/// convert whose pass 1 renders an RGBA intermediate; the only R8 render
/// target reachable with an NV source is a single-pass Grey destination).
fn select_nv_path(
&self,
src: &Tensor<u8>,
src_fmt: PixelFormat,
render_fmt: PixelFormat,
) -> NvConvertPath {
// `ShaderR8` (R8 texelFetch) only applies to SINGLE-PLANE semi-planar
// NV12/NV16/NV24. Everything else routed through this picker —
// RGBA/Grey/YUYV/RGB and true-multiplane NV12 — uses the
// `ExternalSampler` (samplerExternalOES / `draw_camera_texture_eglimage`)
// path, so that is the default.
let shader_capable = matches!(
src_fmt,
PixelFormat::Nv12 | PixelFormat::Nv16 | PixelFormat::Nv24
) && !src.is_multiplane();
if !shader_capable {
return NvConvertPath::ExternalSampler;
}
// From here: single-plane NV12/NV16/NV24 — ShaderR8 is viable. Only NV12
// also has an ExternalSampler path (NV16/NV24 do not).
match self.nv_path_pref {
NvPathPref::ForceShader => NvConvertPath::ShaderR8,
NvPathPref::ForceSampler => {
if src_fmt == PixelFormat::Nv12
&& self.is_vivante
&& render_fmt == PixelFormat::Grey
{
// See the Auto-arm comment: sampler → R8 target wedges the
// GC7000UL. Refuse the force rather than hang the GPU.
log::warn!(
"EDGEFIRST_NV_CONVERT_PATH=sampler refused for NV12→Grey on Vivante \
(samplerExternalOES → R8 render target hangs the GPU); using shader"
);
NvConvertPath::ShaderR8
} else if src_fmt == PixelFormat::Nv12 {
NvConvertPath::ExternalSampler
} else {
log::warn!(
"EDGEFIRST_NV_CONVERT_PATH=sampler unavailable for {src_fmt:?} \
(no external-sampler path); using shader"
);
NvConvertPath::ShaderR8
}
}
// Auto: prefer the portable, colorimetry-exact in-shader ShaderR8
// wherever it is also the fast path (Mali, V3D, Tegra — shader and
// sampler are comparable there, so exactness is free).
//
// EXCEPTION — Vivante (i.MX 8MP): the texelFetch shader is ~12×
// slower than the hardware samplerExternalOES (on-target benchmark:
// NV12 720p convert 29ms shader vs 2.5ms sampler). For single-plane
// 4-aligned NV12 (the sampler import constraint) the pick follows
// the HIGH-PERFORMANCE-default policy (issue #106):
//
// * `ColorimetryMode::Fast` (default): take the sampler for EVERY
// colorimetry — the driver applies its fixed BT.601-limited
// matrix, which is exact for BT.601-limited sources (Phase 2
// probe: ≤1 vs CPU) and approximate for the rest.
// * `ColorimetryMode::Exact` (config/env opt-in): take the sampler
// only when the driver matrix MATCHES the source's resolved
// (encoding, range); everything else renders through the exact
// in-shader matrix, at Vivante's 12× cost.
NvPathPref::Auto => {
// NEVER pair the external sampler with an R8 (Grey) render
// target on Vivante: samplerExternalOES → R8 attachment wedges
// the GC7000UL (the EDGEAI-1180 hang class — found when the
// Fast policy first routed nv12@dma→grey@dma to the sampler;
// the GPU hangs unrecoverably mid-draw). This gate applies in
// BOTH colorimetry modes: the old BT.601-limited carve-out had
// the same latent hang, just unreachable with HD sources.
let vivante_sampler_usable = src_fmt == PixelFormat::Nv12
&& self.is_vivante
&& render_fmt != PixelFormat::Grey
&& src.width().is_some_and(|w| w.is_multiple_of(4));
let take_sampler = vivante_sampler_usable
&& match self.colorimetry_mode {
crate::ColorimetryMode::Fast => true,
crate::ColorimetryMode::Exact => {
let cm = crate::colorimetry::resolve_colorimetry(
src.colorimetry(),
src.height(),
);
cm.encoding == Some(edgefirst_tensor::ColorEncoding::Bt601)
&& cm.range == Some(edgefirst_tensor::ColorRange::Limited)
}
};
if take_sampler {
NvConvertPath::ExternalSampler
} else {
NvConvertPath::ShaderR8
}
}
}
}
#[allow(clippy::too_many_arguments)]
fn convert_to(
&mut self,
src: &Tensor<u8>,
src_fmt: PixelFormat,
dst: &Tensor<u8>,
_dst_fmt: PixelFormat,
is_int8: bool,
rotation: crate::Rotation,
flip: Flip,
crop: ResolvedCrop,
) -> Result<(), crate::Error> {
let dst_w = dst.width().ok_or(Error::NotAnImage)?;
let dst_h = dst.height().ok_or(Error::NotAnImage)?;
self.convert_to_dims(
src,
src_fmt,
dst_w,
dst_h,
dst.view_origin(),
_dst_fmt,
is_int8,
rotation,
flip,
crop,
)
}
/// The body of [`convert_to`], taking the destination geometry directly:
/// renders `src` to the currently-bound FBO. Callers rendering into an
/// engine-internal texture (the fused float two-pass) have no `Tensor<u8>`
/// destination to lend — only its dimensions. `dst_fmt` feeds only
/// `select_nv_path`'s Vivante carve-out, never the render target format
/// (that is whatever the bound FBO holds).
#[allow(clippy::too_many_arguments)]
fn convert_to_dims(
&mut self,
src: &Tensor<u8>,
src_fmt: PixelFormat,
dst_w: usize,
dst_h: usize,
dst_view_origin: Option<edgefirst_tensor::ViewOrigin>,
dst_fmt: PixelFormat,
is_int8: bool,
rotation: crate::Rotation,
flip: Flip,
crop: ResolvedCrop,
) -> Result<(), crate::Error> {
let src_w = src.width().ok_or(Error::NotAnImage)?;
let src_h = src.height().ok_or(Error::NotAnImage)?;
check_gl_error(function!(), line!())?;
// A view()/batch() destination shares ONE parent EGLImage with its
// sibling tiles; the band viewport was set in `setup_renderbuffer_dma`.
// Confine this tile's letterbox `glClear` (below) and draw to the same
// band via `glScissor` so they cannot wipe a sibling. The RAII guard
// disables `SCISSOR_TEST` on every exit (success, `?`, or unwind) so the
// next convert/draw starts from a clean state.
struct ScissorGuard(bool);
impl Drop for ScissorGuard {
fn drop(&mut self) {
if self.0 {
unsafe { edgefirst_gl::gl::Disable(edgefirst_gl::gl::SCISSOR_TEST) };
}
}
}
// Band rect via `region_to_viewport_top_down` — the SAME lowering as
// the band viewport in `bind_dst`'s setup, so scissor and viewport can
// never disagree on the orientation convention.
let _scissor = match dst_view_origin {
Some(vo) => {
let vp = super::render::region_to_viewport_top_down(crate::Region::new(
vo.x, vo.y, dst_w, dst_h,
));
unsafe {
edgefirst_gl::gl::Scissor(vp.x, vp.y, vp.w, vp.h);
edgefirst_gl::gl::Enable(edgefirst_gl::gl::SCISSOR_TEST);
}
ScissorGuard(true)
}
None => ScissorGuard(false),
};
let has_crop = crop
.dst_rect
.is_some_and(|x| x.left != 0 || x.top != 0 || x.width != dst_w || x.height != dst_h);
if has_crop {
if let Some(dst_color) = crop.dst_color {
unsafe {
edgefirst_gl::gl::ClearColor(
dst_color[0] as f32 / 255.0,
dst_color[1] as f32 / 255.0,
dst_color[2] as f32 / 255.0,
dst_color[3] as f32 / 255.0,
);
edgefirst_gl::gl::Clear(edgefirst_gl::gl::COLOR_BUFFER_BIT);
};
}
}
let src_roi = if let Some(crop) = crop.src_rect {
RegionOfInterest::from_crop_clamped(&crop, src_w, src_h)
} else {
RegionOfInterest {
left: 0.,
top: 1.,
right: 1.,
bottom: 0.,
}
};
let cvt_screen_coord = |normalized| normalized * 2.0 - 1.0;
let dst_roi = if let Some(crop) = crop.dst_rect {
RegionOfInterest {
left: cvt_screen_coord(crop.left as f32 / dst_w as f32),
top: cvt_screen_coord((crop.top + crop.height) as f32 / dst_h as f32),
right: cvt_screen_coord((crop.left + crop.width) as f32 / dst_w as f32),
bottom: cvt_screen_coord(crop.top as f32 / dst_h as f32),
}
} else {
RegionOfInterest {
left: -1.,
top: 1.,
right: 1.,
bottom: -1.,
}
};
let rotation_offset = match rotation {
crate::Rotation::None => 0,
crate::Rotation::Clockwise90 => 1,
crate::Rotation::Rotate180 => 2,
crate::Rotation::CounterClockwise90 => 3,
};
if self.gl_context.transfer_backend.is_zero_copy() && src.memory() == TensorMemory::Dma {
// Choose the NV* path (ShaderR8 vs ExternalSampler) honoring the
// EDGEFIRST_NV_CONVERT_PATH preference. See `select_nv_path`: Auto
// prefers the portable, colorimetry-exact in-shader ShaderR8 for
// single-plane NV12/NV16/NV24, using the driver ExternalSampler only
// for true-multiplane NV12 (which ShaderR8 cannot import).
let chosen = self.select_nv_path(src, src_fmt, dst_fmt);
if !Platform::EXTERNAL_OES && chosen == NvConvertPath::ExternalSampler {
// No samplerExternalOES on this platform (ANGLE/Metal):
// packed/Grey zero-copy sources attach as TEXTURE_2D inside
// draw_src_texture; formats it can't take fall back to CPU
// via its error.
self.draw_src_texture(
src,
src_fmt,
src_roi,
dst_roi,
rotation_offset,
flip,
is_int8,
)?;
} else if chosen == NvConvertPath::ShaderR8 {
match self.get_or_create_nv_r8_egl_image(src, src_fmt) {
Ok(r8_egl) => {
tracing::trace!(
path = "ShaderR8",
src_fmt = ?src_fmt,
"image.convert.gl.nv_path"
);
self.last_nv_convert_path = NvConvertPath::ShaderR8;
self.convert_stats.src_imports += 1;
tracing::Span::current().record("src_feed", "import");
self.draw_nv_texture_2d(
src,
src_fmt,
Some(r8_egl),
src_roi,
dst_roi,
rotation_offset,
flip,
is_int8,
)?;
}
Err(e) => {
let src_w = src.width().unwrap_or(0);
let src_h = src.height().unwrap_or(0);
// Path B failed — this means no GPU NV* path is available.
// Record the CPU fallback so tests/profiler can detect it.
self.last_nv_convert_path = NvConvertPath::Cpu;
self.convert_stats.zero_copy_declines += 1;
// Warn once per buffer — a steady-state video pipeline
// hits this every frame with the same buffers, and a
// per-frame warn floods the log. Repeats drop to debug.
if self.nv_import_warned.insert(src.buffer_identity().id()) {
tracing::warn!(
src_fmt = ?src_fmt,
src_w,
src_h,
error = %e,
"Path B R8 EGLImage creation failed for {src_fmt} \
({src_w}x{src_h}); falling back to CPU path (no GPU NV16/NV24)"
);
} else {
tracing::debug!(
src_fmt = ?src_fmt,
src_w,
src_h,
error = %e,
"Path B R8 EGLImage creation failed (repeat)"
);
}
let start = Instant::now();
self.draw_src_texture(
src,
src_fmt,
src_roi,
dst_roi,
rotation_offset,
flip,
is_int8,
)?;
log::debug!("draw_src_texture takes {:?}", start.elapsed());
}
}
} else {
// ExternalSampler path (samplerExternalOES): NV12 (incl.
// multiplane) and all non-shader DMA formats (RGBA/Grey/YUYV);
// single-plane NV12/NV16/NV24 take ShaderR8 above.
match self.get_or_create_egl_image(CacheKind::Src, src, src_fmt) {
Ok(src_egl) => {
if src_fmt == PixelFormat::Nv12 {
tracing::trace!(path = "ExternalSampler", src_fmt = ?src_fmt, "image.convert.gl.nv_path");
self.last_nv_convert_path = NvConvertPath::ExternalSampler;
}
self.convert_stats.src_imports += 1;
tracing::Span::current().record("src_feed", "import");
self.draw_camera_texture_eglimage(
src,
src_fmt,
src_egl,
src_roi,
dst_roi,
rotation_offset,
flip,
is_int8,
)?;
}
Err(e) => {
let src_w = src.width().unwrap_or(0);
let src_h = src.height().unwrap_or(0);
if src_fmt == PixelFormat::Nv12 {
self.last_nv_convert_path = NvConvertPath::Cpu;
}
self.convert_stats.zero_copy_declines += 1;
// Warn once per buffer (see the ShaderR8 arm): repeats
// on the same pooled buffer drop to debug.
if self.nv_import_warned.insert(src.buffer_identity().id()) {
log::warn!(
"EGL image creation failed for {src_fmt} ({src_w}x{src_h}), \
falling back to texture upload (slower): {e}"
);
} else {
log::debug!(
"EGL image creation failed for {src_fmt} ({src_w}x{src_h}) \
(repeat): {e}"
);
}
let start = Instant::now();
self.draw_src_texture(
src,
src_fmt,
src_roi,
dst_roi,
rotation_offset,
flip,
is_int8,
)?;
log::debug!("draw_src_texture takes {:?}", start.elapsed());
}
}
}
} else if matches!(
src_fmt,
PixelFormat::Nv12 | PixelFormat::Nv16 | PixelFormat::Nv24
) && !src.is_multiplane()
{
// Non-DMA (PBO/Sync) single-plane NV*: GPU-convert via the SAME
// ShaderR8 in-shader path used for DMA, but with the combined buffer
// CPU-UPLOADED as R8 instead of EGLImage-imported. This enables the
// NV shaders on backends without DMA-BUF EGLImage import (e.g. orin),
// replacing the old CPU fallback. Multiplane NV12 (separate Y/UV
// buffers) cannot be uploaded as one R8 texture → CPU below.
tracing::trace!(path = "ShaderR8-upload", src_fmt = ?src_fmt, "image.convert.gl.nv_path");
self.last_nv_convert_path = NvConvertPath::ShaderR8;
self.convert_stats.src_uploads += 1;
tracing::Span::current().record("src_feed", "upload");
self.draw_nv_texture_2d(
src,
src_fmt,
None,
src_roi,
dst_roi,
rotation_offset,
flip,
is_int8,
)?;
} else {
// Non-DMA source, non-NV (or multiplane NV): CPU texture-upload path.
if matches!(
src_fmt,
PixelFormat::Nv12 | PixelFormat::Nv16 | PixelFormat::Nv24
) {
self.last_nv_convert_path = NvConvertPath::Cpu;
}
let start = Instant::now();
self.draw_src_texture(
src,
src_fmt,
src_roi,
dst_roi,
rotation_offset,
flip,
is_int8,
)?;
log::debug!("draw_src_texture takes {:?}", start.elapsed());
}
// In a batch (`defer_finish`), skip the per-tile drain so the whole
// batch syncs once via `finish_via_fence` in `convert_batch`. Outside a
// batch this is the standalone convert's completion point and must run.
if !self.defer_finish {
let start = Instant::now();
unsafe { edgefirst_gl::gl::Finish() };
log::debug!("gl_Finish takes {:?}", start.elapsed());
}
check_gl_error(function!(), line!())?;
Ok(())
}
#[allow(clippy::too_many_arguments)]
fn convert_to_planar(
&mut self,
src: &Tensor<u8>,
src_fmt: PixelFormat,
dst: &Tensor<u8>,
dst_fmt: PixelFormat,
is_int8: bool,
rotation: crate::Rotation,
flip: Flip,
crop: ResolvedCrop,
) -> Result<(), crate::Error> {
let src_w = src.width().ok_or(Error::NotAnImage)?;
let src_h = src.height().ok_or(Error::NotAnImage)?;
let dst_w = dst.width().ok_or(Error::NotAnImage)?;
let dst_h = dst.height().ok_or(Error::NotAnImage)?;
// if let Some(crop) = crop.src_rect
// && (crop.left > 0
// || crop.top > 0
// || crop.height < src.height()
// || crop.width < src.width())
// {
// return Err(crate::Error::NotSupported(
// "Cropping in planar RGB mode is not supported".to_string(),
// ));
// }
// if let Some(crop) = crop.dst_rect
// && (crop.left > 0
// || crop.top > 0
// || crop.height < src.height()
// || crop.width < src.width())
// {
// return Err(crate::Error::NotSupported(
// "Cropping in planar RGB mode is not supported".to_string(),
// ));
// }
let alpha = match dst_fmt {
PixelFormat::PlanarRgb => false,
PixelFormat::PlanarRgba => true,
_ => {
return Err(crate::Error::NotSupported(
"Destination format must be PlanarRgb or PlanarRgba".to_string(),
));
}
};
log::trace!(
"convert_to_planar: int8={is_int8}, interpolation={:?}",
self.int8_interpolation_mode
);
let src_roi = if let Some(crop) = crop.src_rect {
RegionOfInterest::from_crop_clamped(&crop, src_w, src_h)
} else {
RegionOfInterest {
left: 0.,
top: 1.,
right: 1.,
bottom: 0.,
}
};
let cvt_screen_coord = |normalized| normalized * 2.0 - 1.0;
let dst_roi = if let Some(crop) = crop.dst_rect {
RegionOfInterest {
left: cvt_screen_coord(crop.left as f32 / dst_w as f32),
top: cvt_screen_coord((crop.top + crop.height) as f32 / dst_h as f32),
right: cvt_screen_coord((crop.left + crop.width) as f32 / dst_w as f32),
bottom: cvt_screen_coord(crop.top as f32 / dst_h as f32),
}
} else {
RegionOfInterest {
left: -1.,
top: 1.,
right: 1.,
bottom: -1.,
}
};
let rotation_offset = match rotation {
crate::Rotation::None => 0,
crate::Rotation::Clockwise90 => 1,
crate::Rotation::Rotate180 => 2,
crate::Rotation::CounterClockwise90 => 3,
};
let has_crop = crop
.dst_rect
.is_some_and(|x| x.left != 0 || x.top != 0 || x.width != dst_w || x.height != dst_h);
if has_crop {
if let Some(dst_color) = crop.dst_color {
self.clear_rect_planar(
dst_w,
dst_h,
dst_roi,
[
dst_color[0] as f32 / 255.0,
dst_color[1] as f32 / 255.0,
dst_color[2] as f32 / 255.0,
dst_color[3] as f32 / 255.0,
],
alpha,
)?;
}
}
let src_key = BufferImportKey::from_tensor(src, src_fmt, false);
let src_egl = self.get_or_create_egl_image(CacheKind::Src, src, src_fmt)?;
self.draw_camera_texture_to_rgb_planar(
src_key,
src_egl,
src_roi,
dst_roi,
rotation_offset,
flip,
alpha,
is_int8,
)?;
unsafe { edgefirst_gl::gl::Finish() };
check_gl_error(function!(), line!())?;
Ok(())
}
/// Render packed RGB (or int8 RGB) to a DMA destination buffer using a
/// two-pass architecture:
///
/// **Pass 1:** Render source → intermediate RGBA texture via `convert_to()`
/// (reuses the battle-tested RGBA path with full crop/letterbox/rotation/flip).
///
/// **Pass 2:** Pack intermediate RGBA → RGB DMA destination using a simple
/// packing shader with 2D sampler. The destination DMA buffer is reinterpreted
/// as RGBA8 at (W*3/4) x H dimensions.
#[allow(clippy::too_many_arguments)]
fn convert_to_packed_rgb(
&mut self,
src: &Tensor<u8>,
src_fmt: PixelFormat,
dst: &mut Tensor<u8>,
dst_fmt: PixelFormat,
is_int8: bool,
rotation: crate::Rotation,
flip: Flip,
crop: ResolvedCrop,
) -> crate::Result<()> {
let dst_w = dst.width().ok_or(Error::NotAnImage)?;
let dst_h = dst.height().ok_or(Error::NotAnImage)?;
// Canonical RGBA8888-packed geometry (single source of truth shared
// with the Android AHardwareBuffer allocation side — the same rule
// that keeps the F16 packing from drifting between crates).
let layout = edgefirst_tensor::packed_rgb888_layout(dst_w, dst_h).ok_or_else(|| {
crate::Error::NotSupported(format!(
"Packed RGB requires width%4==0 (W*3 bytes must divide into \
whole RGBA8888 texels), got width={dst_w}"
))
})?;
let render_w = layout.surface_w;
let render_h = layout.surface_h;
log::debug!(
"convert_to_packed_rgb: {dst_w}x{dst_h} -> {render_w}x{render_h} two-pass int8={is_int8}",
);
// --- Pass 1: Render source → intermediate RGBA texture ---
let _pass1 =
tracing::trace_span!("image.convert.gl.pack_rgb.pass1_rgba", dst_w, dst_h).entered();
self.ensure_packed_rgb_intermediate(dst_w, dst_h)?;
self.packed_rgb_fbo.bind();
unsafe {
edgefirst_gl::gl::FramebufferTexture2D(
edgefirst_gl::gl::FRAMEBUFFER,
edgefirst_gl::gl::COLOR_ATTACHMENT0,
edgefirst_gl::gl::TEXTURE_2D,
self.packed_rgb_intermediate_tex.id,
0,
);
check_gl_error(function!(), line!())?;
edgefirst_gl::gl::Viewport(0, 0, dst_w as i32, dst_h as i32);
}
// convert_to() renders to the currently-bound FBO (packed_rgb_fbo → intermediate).
// It uses dst only for width/height in ROI coordinate math.
// Handles: source binding (DMA EGLImage or upload), crop, letterbox, rotation, flip.
// Pass 1 renders UN-biased (is_int8 = false): the int8 XOR-0x80 bias is
// applied once, by pass 2's packing shader.
//
// Pass 1 must NOT glFinish (convert_to's standalone-boundary sync):
// same-context command ordering already guarantees pass 2 samples the
// finished intermediate, and the convert syncs once at pass 2's end.
// The flag restores before `?` so an error cannot leak defer state.
let saved_defer = self.defer_finish;
self.defer_finish = true;
let pass1 = self.convert_to(src, src_fmt, dst, dst_fmt, false, rotation, flip, crop);
self.defer_finish = saved_defer;
pass1?;
drop(_pass1);
// --- Pass 2: Pack intermediate RGBA → RGB DMA destination ---
let _pass2 =
tracing::trace_span!("image.convert.gl.pack_rgb.pass2_pack", render_w, render_h)
.entered();
self.convert_fbo.bind();
let dest_egl = self.get_or_create_egl_image_rgb(
dst,
dst_fmt,
render_w,
render_h,
super::platform::PackedImportFormat::Rgba8888,
)?;
unsafe {
match self.cached_dst_renderbuffer(dst, dst_fmt) {
Some(rbo) => {
edgefirst_gl::gl::BindRenderbuffer(edgefirst_gl::gl::RENDERBUFFER, rbo);
edgefirst_gl::gl::FramebufferRenderbuffer(
edgefirst_gl::gl::FRAMEBUFFER,
edgefirst_gl::gl::COLOR_ATTACHMENT0,
edgefirst_gl::gl::RENDERBUFFER,
rbo,
);
}
None => {
edgefirst_gl::gl::ActiveTexture(edgefirst_gl::gl::TEXTURE0);
edgefirst_gl::gl::BindTexture(
edgefirst_gl::gl::TEXTURE_2D,
self.render_texture.id,
);
super::core::set_tex_filter(
edgefirst_gl::gl::TEXTURE_2D,
edgefirst_gl::gl::NEAREST,
);
Platform::attach_tex_image_2d(&self.gl_context, dest_egl)?;
// Raw re-target bypasses bind_egl_image's key tracking:
// drop the cached key so a later bind_egl_image on this
// texture cannot "reuse" a binding this call replaced
// (silent write into the wrong destination buffer).
self.render_texture.invalidate_egl_binding();
edgefirst_gl::gl::FramebufferTexture2D(
edgefirst_gl::gl::FRAMEBUFFER,
edgefirst_gl::gl::COLOR_ATTACHMENT0,
edgefirst_gl::gl::TEXTURE_2D,
self.render_texture.id,
0,
);
}
}
check_gl_error(function!(), line!())?;
edgefirst_gl::gl::Viewport(0, 0, render_w as i32, render_h as i32);
}
// Bind intermediate RGBA texture as source for the packing shader
let program = if is_int8 {
&self.packed_rgba8_int8_program_2d
} else {
&self.packed_rgba8_program_2d
};
unsafe {
edgefirst_gl::gl::UseProgram(program.id);
edgefirst_gl::gl::ActiveTexture(edgefirst_gl::gl::TEXTURE1);
edgefirst_gl::gl::BindTexture(
edgefirst_gl::gl::TEXTURE_2D,
self.packed_rgb_intermediate_tex.id,
);
super::core::set_tex_filter(edgefirst_gl::gl::TEXTURE_2D, edgefirst_gl::gl::NEAREST);
}
// (`tex` = unit 1 is constant per program, uploaded at link time.)
// Draw full-viewport quad to pack RGBA→RGB
self.draw_fullscreen_quad()?;
// Pass 2 bound the intermediate on TEXTURE1; restore unit 0 as the
// active unit. Draw/setup sites select their unit before binding, but
// the processor-wide invariant between operations is "unit 0 active" —
// leaking unit 1 here is what broke the second heap-source convert
// (GL_INVALID_VALUE upload into the wrong texture).
unsafe { edgefirst_gl::gl::ActiveTexture(edgefirst_gl::gl::TEXTURE0) };
unsafe { edgefirst_gl::gl::Finish() };
check_gl_error(function!(), line!())?;
Ok(())
}
/// Two-pass NV12→PlanarRgb workaround for Vivante GPU.
///
/// Single-pass NV12→PlanarRgb causes an unrecoverable GPU hang on the
/// Verisilicon/Vivante GC7000UL. This method splits the operation:
///
/// **Pass 1:** NV12→RGBA into `packed_rgb_intermediate_tex` via `convert_to()`
/// (full resize/crop/rotation/flip, no int8 bias).
///
/// **Pass 2:** RGBA→PlanarRgb from intermediate to DMA destination via
/// [`draw_intermediate_to_rgb_planar`] (channel deinterleave + optional int8 bias).
#[allow(clippy::too_many_arguments)]
fn convert_nv_to_planar_two_pass(
&mut self,
src: &Tensor<u8>,
src_fmt: PixelFormat,
dst: &mut Tensor<u8>,
dst_fmt: PixelFormat,
is_int8: bool,
rotation: crate::Rotation,
flip: Flip,
crop: ResolvedCrop,
) -> crate::Result<()> {
let dst_w = dst.width().ok_or(Error::NotAnImage)?;
let dst_h = dst.height().ok_or(Error::NotAnImage)?;
let alpha = match dst_fmt {
PixelFormat::PlanarRgb => false,
PixelFormat::PlanarRgba => true,
_ => {
return Err(crate::Error::NotSupported(
"Destination format must be PlanarRgb or PlanarRgba".to_string(),
));
}
};
log::debug!(
"convert_nv_to_planar_two_pass: {src_fmt}→{dst_fmt} {dst_w}x{dst_h} \
int8={is_int8} (Vivante two-pass workaround)",
);
// --- Pass 1: NV12→RGBA into intermediate texture ---
// No int8 bias here — bias is applied in pass 2's planar shader.
let _pass1 = tracing::trace_span!("image.convert.gl.nv_to_planar.pass1_rgba", dst_w, dst_h)
.entered();
self.ensure_packed_rgb_intermediate(dst_w, dst_h)?;
self.packed_rgb_fbo.bind();
unsafe {
edgefirst_gl::gl::FramebufferTexture2D(
edgefirst_gl::gl::FRAMEBUFFER,
edgefirst_gl::gl::COLOR_ATTACHMENT0,
edgefirst_gl::gl::TEXTURE_2D,
self.packed_rgb_intermediate_tex.id,
0,
);
check_gl_error(function!(), line!())?;
edgefirst_gl::gl::Viewport(0, 0, dst_w as i32, dst_h as i32);
}
// convert_to() renders to the currently-bound FBO (packed_rgb_fbo → intermediate RGBA).
// Note: dst_fmt is passed but ignored (_dst_fmt in convert_to's signature) — the actual
// output format is RGBA because we bound packed_rgb_fbo above. dst is used only for
// width/height in ROI coordinate math.
// Pass 1 renders UN-biased (is_int8 = false): the int8 XOR-0x80 bias is
// applied once, by pass 2's planar deinterleave shader.
//
// Pass 1 must NOT glFinish (convert_to's standalone-boundary sync):
// same-context command ordering already guarantees pass 2 samples the
// finished intermediate, and the convert syncs once at pass 2's end.
let saved_defer = self.defer_finish;
self.defer_finish = true;
let pass1 = self.convert_to(src, src_fmt, dst, dst_fmt, false, rotation, flip, crop);
self.defer_finish = saved_defer;
pass1?;
drop(_pass1);
// --- Pass 2: RGBA→PlanarRgb to DMA destination ---
// bind_dst rebinds convert_fbo with the DMA destination EGLImage,
// replacing packed_rgb_fbo that was active during pass 1. It also sets the viewport
// to (dst_w, dst_h * 3) for the tall R8 planar renderbuffer.
let _pass2 = tracing::trace_span!(
"image.convert.gl.nv_to_planar.pass2_deinterleave",
dst_w,
dst_h
)
.entered();
self.bind_dst(dst, dst_fmt, crop)?;
// Pass 2 is a fullscreen blit from the intermediate to the planar
// destination. Pass 1 (convert_to above) already placed the image
// content at the correct letterbox position within the intermediate
// AND filled the padding region with the requested dst_color.
// Re-applying the dst_rect crop here would map the full intermediate
// (whose content is already correctly placed) into only the content
// sub-region, shrinking the image by the letterbox content fraction
// a second time. Observed downstream as bounding boxes compressed by
// exactly (content/canvas) in the padded dimension on i.MX 8M Plus.
//
// No int8 bias-clear here either: pass 2 performs no clear, and the
// planar deinterleave shader applies the int8 bias itself (is_int8
// flag on the draw below).
let dst_roi = RegionOfInterest {
left: -1.,
top: 1.,
right: 1.,
bottom: -1.,
};
self.draw_intermediate_to_rgb_planar(dst_roi, alpha, is_int8)?;
unsafe { edgefirst_gl::gl::Finish() };
check_gl_error(function!(), line!())?;
Ok(())
}
/// Allocates or resizes the intermediate RGBA texture for two-pass packed RGB.
fn ensure_packed_rgb_intermediate(&mut self, width: usize, height: usize) -> crate::Result<()> {
if self.packed_rgb_intermediate_size == (width, height) {
return Ok(());
}
unsafe {
edgefirst_gl::gl::BindTexture(
edgefirst_gl::gl::TEXTURE_2D,
self.packed_rgb_intermediate_tex.id,
);
super::core::set_tex_filter(edgefirst_gl::gl::TEXTURE_2D, edgefirst_gl::gl::NEAREST);
edgefirst_gl::gl::TexImage2D(
edgefirst_gl::gl::TEXTURE_2D,
0,
edgefirst_gl::gl::RGBA as i32,
width as i32,
height as i32,
0,
edgefirst_gl::gl::RGBA,
edgefirst_gl::gl::UNSIGNED_BYTE,
std::ptr::null(),
);
check_gl_error(function!(), line!())?;
}
self.packed_rgb_intermediate_size = (width, height);
Ok(())
}
/// Draw a fullscreen quad for the currently-bound shader program.
/// Used by the pass-2 packing shader in the two-pass packed RGB pipeline.
fn draw_fullscreen_quad(&self) -> Result<(), crate::Error> {
unsafe {
edgefirst_gl::gl::BindBuffer(edgefirst_gl::gl::ARRAY_BUFFER, self.vertex_buffer.id);
edgefirst_gl::gl::EnableVertexAttribArray(self.vertex_buffer.buffer_index);
let vertices: [f32; 12] = [
-1.0, 1.0, 0.0, // top-left
1.0, 1.0, 0.0, // top-right
1.0, -1.0, 0.0, // bottom-right
-1.0, -1.0, 0.0, // bottom-left
];
edgefirst_gl::gl::BufferSubData(
edgefirst_gl::gl::ARRAY_BUFFER,
0,
(size_of::<f32>() * vertices.len()) as isize,
vertices.as_ptr() as *const c_void,
);
edgefirst_gl::gl::BindBuffer(edgefirst_gl::gl::ARRAY_BUFFER, self.texture_buffer.id);
edgefirst_gl::gl::EnableVertexAttribArray(self.texture_buffer.buffer_index);
// Texture coordinates (the packed shader uses gl_FragCoord, not tc,
// but we still need valid buffers for the vertex attribute layout)
let tex_coords: [f32; 8] = [0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0];
edgefirst_gl::gl::BufferSubData(
edgefirst_gl::gl::ARRAY_BUFFER,
0,
(size_of::<f32>() * tex_coords.len()) as isize,
tex_coords.as_ptr() as *const c_void,
);
let indices: [u32; 4] = [0, 1, 2, 3];
edgefirst_gl::gl::DrawElements(
edgefirst_gl::gl::TRIANGLE_FAN,
indices.len() as i32,
edgefirst_gl::gl::UNSIGNED_INT,
indices.as_ptr() as *const c_void,
);
}
check_gl_error(function!(), line!())?;
Ok(())
}
fn clear_rect_planar(
&self,
width: usize,
height: usize,
dst_roi: RegionOfInterest,
color: [f32; 4],
alpha: bool,
) -> Result<(), Error> {
if !alpha && color[0] == color[1] && color[1] == color[2] {
unsafe {
edgefirst_gl::gl::ClearColor(color[0], color[0], color[0], 1.0);
edgefirst_gl::gl::Clear(edgefirst_gl::gl::COLOR_BUFFER_BIT);
};
}
let split = if alpha { 4 } else { 3 };
unsafe {
edgefirst_gl::gl::Enable(edgefirst_gl::gl::SCISSOR_TEST);
let x = (((dst_roi.left + 1.0) / 2.0) * width as f32).round() as i32;
let y = (((dst_roi.bottom + 1.0) / 2.0) * height as f32).round() as i32;
let width = (((dst_roi.right - dst_roi.left) / 2.0) * width as f32).round() as i32;
let height = (((dst_roi.top - dst_roi.bottom) / 2.0) * height as f32 / split as f32)
.round() as i32;
for (i, c) in color.iter().enumerate().take(split) {
edgefirst_gl::gl::Scissor(x, y + i as i32 * height, width, height);
edgefirst_gl::gl::ClearColor(*c, *c, *c, 1.0);
edgefirst_gl::gl::Clear(edgefirst_gl::gl::COLOR_BUFFER_BIT);
}
edgefirst_gl::gl::Disable(edgefirst_gl::gl::SCISSOR_TEST);
}
Ok(())
}
#[allow(clippy::too_many_arguments)]
fn draw_camera_texture_to_rgb_planar(
&mut self,
src_key: BufferImportKey,
egl_img: PlatformHandle,
src_roi: RegionOfInterest,
mut dst_roi: RegionOfInterest,
rotation_offset: usize,
flip: Flip,
alpha: bool,
int8: bool,
) -> Result<(), Error> {
let texture_target = edgefirst_gl::gl::TEXTURE_EXTERNAL_OES;
match flip {
Flip::None => {}
Flip::Vertical => {
std::mem::swap(&mut dst_roi.top, &mut dst_roi.bottom);
}
Flip::Horizontal => {
std::mem::swap(&mut dst_roi.left, &mut dst_roi.right);
}
}
let program_id = if int8 {
&self.texture_program_planar_int8
} else {
&self.texture_program_planar
}
.as_ref()
.ok_or_else(|| {
Error::NotSupported("external-OES planar program unavailable on this platform".into())
})?
.id;
unsafe {
edgefirst_gl::gl::UseProgram(program_id);
edgefirst_gl::gl::ActiveTexture(edgefirst_gl::gl::TEXTURE0);
edgefirst_gl::gl::BindTexture(texture_target, self.camera_eglimage_texture.id);
super::core::set_tex_filter(texture_target, edgefirst_gl::gl::LINEAR);
edgefirst_gl::gl::TexParameteri(
texture_target,
edgefirst_gl::gl::TEXTURE_WRAP_S,
edgefirst_gl::gl::CLAMP_TO_EDGE as i32,
);
edgefirst_gl::gl::TexParameteri(
texture_target,
edgefirst_gl::gl::TEXTURE_WRAP_T,
edgefirst_gl::gl::CLAMP_TO_EDGE as i32,
);
if self.camera_eglimage_texture.bind_egl_image_external(
&self.gl_context,
src_key,
egl_img,
)? {
check_gl_error(function!(), line!())?;
log::trace!(
"draw_camera_planar: bound new src EGLImage id={:#x}",
src_key.luma_id
);
} else {
log::trace!(
"draw_camera_planar: reusing bound src EGLImage id={:#x}",
src_key.luma_id
);
}
let y_centers = if alpha {
vec![-3.0 / 4.0, -1.0 / 4.0, 1.0 / 4.0, 3.0 / 4.0]
} else {
vec![-2.0 / 3.0, 0.0, 2.0 / 3.0]
};
let swizzles = [
edgefirst_gl::gl::RED,
edgefirst_gl::gl::GREEN,
edgefirst_gl::gl::BLUE,
edgefirst_gl::gl::ALPHA,
];
// starts from bottom
for (i, y_center) in y_centers.iter().enumerate() {
edgefirst_gl::gl::BindBuffer(edgefirst_gl::gl::ARRAY_BUFFER, self.vertex_buffer.id);
edgefirst_gl::gl::EnableVertexAttribArray(self.vertex_buffer.buffer_index);
let camera_vertices: [f32; 12] = [
dst_roi.left,
dst_roi.top / 3.0 + y_center,
0., // left top
dst_roi.right,
dst_roi.top / 3.0 + y_center,
0., // right top
dst_roi.right,
dst_roi.bottom / 3.0 + y_center,
0., // right bottom
dst_roi.left,
dst_roi.bottom / 3.0 + y_center,
0., // left bottom
];
edgefirst_gl::gl::BufferData(
edgefirst_gl::gl::ARRAY_BUFFER,
(size_of::<f32>() * camera_vertices.len()) as isize,
camera_vertices.as_ptr() as *const c_void,
edgefirst_gl::gl::DYNAMIC_DRAW,
);
edgefirst_gl::gl::BindBuffer(
edgefirst_gl::gl::ARRAY_BUFFER,
self.texture_buffer.id,
);
edgefirst_gl::gl::EnableVertexAttribArray(self.texture_buffer.buffer_index);
let texture_vertices: [f32; 16] = [
src_roi.left,
src_roi.top,
src_roi.right,
src_roi.top,
src_roi.right,
src_roi.bottom,
src_roi.left,
src_roi.bottom,
src_roi.left,
src_roi.top,
src_roi.right,
src_roi.top,
src_roi.right,
src_roi.bottom,
src_roi.left,
src_roi.bottom,
];
edgefirst_gl::gl::BufferData(
edgefirst_gl::gl::ARRAY_BUFFER,
(size_of::<f32>() * 8) as isize,
(texture_vertices[(rotation_offset * 2)..]).as_ptr() as *const c_void,
edgefirst_gl::gl::DYNAMIC_DRAW,
);
let vertices_index: [u32; 4] = [0, 1, 2, 3];
// self.texture_program_planar
// .load_uniform_1i(c"color_index", 2 - i as i32);
edgefirst_gl::gl::TexParameteri(
texture_target,
edgefirst_gl::gl::TEXTURE_SWIZZLE_R,
swizzles[i] as i32,
);
edgefirst_gl::gl::DrawElements(
edgefirst_gl::gl::TRIANGLE_FAN,
vertices_index.len() as i32,
edgefirst_gl::gl::UNSIGNED_INT,
vertices_index.as_ptr() as *const c_void,
);
}
// Reset the texture swizzle to identity before returning. The
// loop above left `TEXTURE_SWIZZLE_R` pointing at the last
// requested planar channel (`GL_BLUE` for RGB, `GL_ALPHA` when
// `alpha` is true). The GLES spec says `GL_TEXTURE_SWIZZLE_*` is
// undefined for `GL_TEXTURE_EXTERNAL_OES`, but NXP Vivante and
// Mali drivers honor it on external textures and the swizzle
// persists across subsequent samples — including the bg blit in
// `draw_decoded_masks`, which then channel-permutes the entire
// overlay's background. Restoring identity before any later
// sampler sees this texture is the safe move.
edgefirst_gl::gl::TexParameteri(
texture_target,
edgefirst_gl::gl::TEXTURE_SWIZZLE_R,
edgefirst_gl::gl::RED as i32,
);
check_gl_error(function!(), line!())?;
}
Ok(())
}
/// Draw the intermediate RGBA texture to planar RGB output.
///
/// Pass 2 of the two-pass NV12→PlanarRgb workaround for Vivante GPUs.
/// Mirrors [`draw_camera_texture_to_rgb_planar`] but sources from
/// `packed_rgb_intermediate_tex` (a `TEXTURE_2D`) instead of an EGLImage
/// (`TEXTURE_EXTERNAL_OES`). No rotation/flip — those were handled in pass 1.
fn draw_intermediate_to_rgb_planar(
&self,
dst_roi: RegionOfInterest,
alpha: bool,
int8: bool,
) -> Result<(), Error> {
let texture_target = edgefirst_gl::gl::TEXTURE_2D;
unsafe {
let program = if int8 {
&self.texture_program_planar_int8_2d
} else {
&self.texture_program_planar_2d
};
edgefirst_gl::gl::UseProgram(program.id);
edgefirst_gl::gl::ActiveTexture(edgefirst_gl::gl::TEXTURE0);
edgefirst_gl::gl::BindTexture(texture_target, self.packed_rgb_intermediate_tex.id);
super::core::set_tex_filter_clamp(texture_target, edgefirst_gl::gl::LINEAR);
// (`tex` = unit 0 is constant per program, uploaded at link time.)
check_gl_error(function!(), line!())?;
let y_centers = if alpha {
vec![-3.0 / 4.0, -1.0 / 4.0, 1.0 / 4.0, 3.0 / 4.0]
} else {
vec![-2.0 / 3.0, 0.0, 2.0 / 3.0]
};
let swizzles = [
edgefirst_gl::gl::RED,
edgefirst_gl::gl::GREEN,
edgefirst_gl::gl::BLUE,
edgefirst_gl::gl::ALPHA,
];
// Source ROI is always fullscreen (intermediate is already at destination size)
let src_roi = RegionOfInterest {
left: 0.0,
top: 1.0,
right: 1.0,
bottom: 0.0,
};
for (i, y_center) in y_centers.iter().enumerate() {
edgefirst_gl::gl::BindBuffer(edgefirst_gl::gl::ARRAY_BUFFER, self.vertex_buffer.id);
edgefirst_gl::gl::EnableVertexAttribArray(self.vertex_buffer.buffer_index);
let camera_vertices: [f32; 12] = [
dst_roi.left,
dst_roi.top / 3.0 + y_center,
0., // left top
dst_roi.right,
dst_roi.top / 3.0 + y_center,
0., // right top
dst_roi.right,
dst_roi.bottom / 3.0 + y_center,
0., // right bottom
dst_roi.left,
dst_roi.bottom / 3.0 + y_center,
0., // left bottom
];
edgefirst_gl::gl::BufferData(
edgefirst_gl::gl::ARRAY_BUFFER,
(size_of::<f32>() * camera_vertices.len()) as isize,
camera_vertices.as_ptr() as *const c_void,
edgefirst_gl::gl::DYNAMIC_DRAW,
);
edgefirst_gl::gl::BindBuffer(
edgefirst_gl::gl::ARRAY_BUFFER,
self.texture_buffer.id,
);
edgefirst_gl::gl::EnableVertexAttribArray(self.texture_buffer.buffer_index);
// No rotation — pass 1 already handled it. Use base texture coords directly.
let texture_vertices: [f32; 8] = [
src_roi.left,
src_roi.top,
src_roi.right,
src_roi.top,
src_roi.right,
src_roi.bottom,
src_roi.left,
src_roi.bottom,
];
edgefirst_gl::gl::BufferData(
edgefirst_gl::gl::ARRAY_BUFFER,
(size_of::<f32>() * texture_vertices.len()) as isize,
texture_vertices.as_ptr() as *const c_void,
edgefirst_gl::gl::DYNAMIC_DRAW,
);
let vertices_index: [u32; 4] = [0, 1, 2, 3];
edgefirst_gl::gl::TexParameteri(
texture_target,
edgefirst_gl::gl::TEXTURE_SWIZZLE_R,
swizzles[i] as i32,
);
edgefirst_gl::gl::DrawElements(
edgefirst_gl::gl::TRIANGLE_FAN,
vertices_index.len() as i32,
edgefirst_gl::gl::UNSIGNED_INT,
vertices_index.as_ptr() as *const c_void,
);
}
// Reset the texture swizzle to identity (see the matching
// comment in `draw_camera_texture_to_rgb_planar` above). This
// path operates on a `TEXTURE_2D` intermediate, which honors the
// swizzle per spec — leaving `TEXTURE_SWIZZLE_R` set to the last
// planar channel selected (for example `GL_BLUE` for RGB or
// `GL_ALPHA` for RGBA) poisons every later sampler bound to this
// texture object.
edgefirst_gl::gl::TexParameteri(
texture_target,
edgefirst_gl::gl::TEXTURE_SWIZZLE_R,
edgefirst_gl::gl::RED as i32,
);
check_gl_error(function!(), line!())?;
}
Ok(())
}
#[allow(clippy::too_many_arguments)]
fn draw_src_texture(
&mut self,
src: &Tensor<u8>,
src_fmt: PixelFormat,
src_roi: RegionOfInterest,
mut dst_roi: RegionOfInterest,
rotation_offset: usize,
flip: Flip,
is_int8: bool,
) -> Result<(), Error> {
let src_w = src.width().ok_or(Error::NotAnImage)?;
let src_h = src.height().ok_or(Error::NotAnImage)?;
let texture_target = edgefirst_gl::gl::TEXTURE_2D;
// Zero-copy source attach: on platforms whose imports bind as
// TEXTURE_2D (macOS IOSurface), a Dma-memory source is imported
// and attached to the source texture instead of being uploaded.
// Import errors fall back to the upload below (the map() of an
// IOSurface tensor is always valid); YUYV has no upload arm and
// is accepted only when its RG attach succeeds.
let zero_copy_attach = if !self.gl_context.transfer_backend.is_dma()
&& self.gl_context.transfer_backend.is_zero_copy()
&& src.memory() == TensorMemory::Dma
&& matches!(
src_fmt,
PixelFormat::Rgba | PixelFormat::Grey | PixelFormat::Yuyv
) {
let key = BufferImportKey::from_tensor(src, src_fmt, false);
match self.get_or_create_egl_image(CacheKind::Src, src, src_fmt) {
Ok(handle) => Some((key, handle)),
Err(e) => {
self.convert_stats.zero_copy_declines += 1;
log::debug!("zero-copy source import failed ({e:?}); uploading instead");
None
}
}
} else {
None
};
let texture_format = match src_fmt {
PixelFormat::Rgb => edgefirst_gl::gl::RGB,
PixelFormat::Rgba => edgefirst_gl::gl::RGBA,
PixelFormat::Grey => edgefirst_gl::gl::RED,
// YUYV samples as RG (R=Y, G=alternating chroma) — zero-copy
// attach only; there is deliberately no upload arm yet.
PixelFormat::Yuyv if zero_copy_attach.is_some() => edgefirst_gl::gl::RG,
_ => {
return Err(Error::NotSupported(format!(
"draw_src_texture does not support {src_fmt:?} (use DMA-BUF path for YUV)",
)));
}
};
// Draw-time program selection: the int8 program is the same shader
// plus the XOR-0x80 bias, selected here instead of swap-and-restore
// around the render.
let program_id = if src_fmt == PixelFormat::Yuyv {
if is_int8 {
return Err(Error::NotSupported(
"YUYV zero-copy source has no int8 program; CPU fallback handles it".into(),
));
}
self.yuyv_program_2d.id
} else if is_int8 {
self.texture_int8_program.id
} else {
self.texture_program.id
};
unsafe {
edgefirst_gl::gl::UseProgram(program_id);
if src_fmt == PixelFormat::Yuyv {
// YUYV program inputs: source texel grid + the YUV→RGB
// matrix/range resolved from the tensor colorimetry (same
// resolution rule as the NV paths).
let cm = crate::colorimetry::resolve_colorimetry(src.colorimetry(), src.height());
let coeffs = crate::colorimetry::yuv_to_rgb_coeffs(
cm.encoding
.unwrap_or(edgefirst_tensor::ColorEncoding::Bt709),
cm.range.unwrap_or(edgefirst_tensor::ColorRange::Limited),
);
let [src_size, y_offset, y_scale, c_vr, c_ug, c_vg, c_ub] = self.yuyv_2d_locs;
edgefirst_gl::gl::Uniform2f(src_size, src_w as f32, src_h as f32);
edgefirst_gl::gl::Uniform1f(y_offset, coeffs.y_offset);
edgefirst_gl::gl::Uniform1f(y_scale, coeffs.y_scale);
edgefirst_gl::gl::Uniform1f(c_vr, coeffs.c_vr);
edgefirst_gl::gl::Uniform1f(c_ug, coeffs.c_ug);
edgefirst_gl::gl::Uniform1f(c_vg, coeffs.c_vg);
edgefirst_gl::gl::Uniform1f(c_ub, coeffs.c_ub);
}
edgefirst_gl::gl::ActiveTexture(edgefirst_gl::gl::TEXTURE0);
edgefirst_gl::gl::BindTexture(texture_target, self.camera_normal_texture.id);
super::core::set_tex_filter_clamp(texture_target, edgefirst_gl::gl::LINEAR);
if src_fmt == PixelFormat::Grey {
for swizzle in [
edgefirst_gl::gl::TEXTURE_SWIZZLE_R,
edgefirst_gl::gl::TEXTURE_SWIZZLE_G,
edgefirst_gl::gl::TEXTURE_SWIZZLE_B,
] {
edgefirst_gl::gl::TexParameteri(
edgefirst_gl::gl::TEXTURE_2D,
swizzle,
edgefirst_gl::gl::RED as i32,
);
}
} else {
for (swizzle, src_comp) in [
(edgefirst_gl::gl::TEXTURE_SWIZZLE_R, edgefirst_gl::gl::RED),
(edgefirst_gl::gl::TEXTURE_SWIZZLE_G, edgefirst_gl::gl::GREEN),
(edgefirst_gl::gl::TEXTURE_SWIZZLE_B, edgefirst_gl::gl::BLUE),
] {
edgefirst_gl::gl::TexParameteri(
edgefirst_gl::gl::TEXTURE_2D,
swizzle,
src_comp as i32,
);
}
}
// The source map exposes the full row-padded allocation (DMA/IOSurface
// tensors carry a 64-byte-aligned pitch). TexImage2D otherwise reads
// `src_w` tight pixels per row from a padded buffer, shearing every row
// after the first — the failure mode for odd-width Grey/RGB, whose
// 1-/3-bpp pitch is not 4-aligned so they can't take the stride-aware
// EGLImage path. Tell GL the real row length (in pixels) so it skips
// the padding; reset afterwards so other uploads stay tight.
if let Some((key, handle)) = zero_copy_attach {
self.camera_normal_texture
.bind_egl_image(&self.gl_context, key, handle)?;
// Poison the upload-tracking dims: a later upload on this
// texture must TexImage2D fresh storage, never
// TexSubImage2D into the attached client buffer.
self.camera_normal_texture.target = 0;
self.convert_stats.src_imports += 1;
tracing::Span::current().record("src_feed", "import");
} else {
let src_bpp = src_fmt.channels().max(1);
// A recorded pitch that is not a whole number of pixels
// cannot be expressed via UNPACK_ROW_LENGTH (which counts
// pixels) — decline to the CPU backend rather than upload
// sheared rows. Reachable on Android, where gralloc may pad
// the RGB-in-RGBA8888 surface to a byte pitch that 3 does
// not divide.
if let Some(s) = src.effective_row_stride() {
if !s.is_multiple_of(src_bpp) {
return Err(Error::NotSupported(format!(
"source row pitch {s} B is not a whole number of \
{src_fmt:?} pixels ({src_bpp} B/px); upload would \
shear rows"
)));
}
}
self.convert_stats.src_uploads += 1;
tracing::Span::current().record("src_feed", "upload");
let row_len_px = src
.effective_row_stride()
.map(|s| s / src_bpp)
.filter(|&px| px != src_w)
.unwrap_or(0);
edgefirst_gl::gl::PixelStorei(
edgefirst_gl::gl::UNPACK_ROW_LENGTH,
row_len_px as i32,
);
self.camera_normal_texture.update_texture(
texture_target,
src_w,
src_h,
texture_format,
&src.map_read()?,
);
edgefirst_gl::gl::PixelStorei(edgefirst_gl::gl::UNPACK_ROW_LENGTH, 0);
}
edgefirst_gl::gl::BindBuffer(edgefirst_gl::gl::ARRAY_BUFFER, self.vertex_buffer.id);
edgefirst_gl::gl::EnableVertexAttribArray(self.vertex_buffer.buffer_index);
match flip {
Flip::None => {}
Flip::Vertical => {
std::mem::swap(&mut dst_roi.top, &mut dst_roi.bottom);
}
Flip::Horizontal => {
std::mem::swap(&mut dst_roi.left, &mut dst_roi.right);
}
}
let camera_vertices: [f32; 12] = [
dst_roi.left,
dst_roi.top,
0., // left top
dst_roi.right,
dst_roi.top,
0., // right top
dst_roi.right,
dst_roi.bottom,
0., // right bottom
dst_roi.left,
dst_roi.bottom,
0., // left bottom
];
edgefirst_gl::gl::BufferData(
edgefirst_gl::gl::ARRAY_BUFFER,
(size_of::<f32>() * camera_vertices.len()) as isize,
camera_vertices.as_ptr() as *const c_void,
edgefirst_gl::gl::DYNAMIC_DRAW,
);
edgefirst_gl::gl::BindBuffer(edgefirst_gl::gl::ARRAY_BUFFER, self.texture_buffer.id);
edgefirst_gl::gl::EnableVertexAttribArray(self.texture_buffer.buffer_index);
let texture_vertices: [f32; 16] = [
src_roi.left,
src_roi.top,
src_roi.right,
src_roi.top,
src_roi.right,
src_roi.bottom,
src_roi.left,
src_roi.bottom,
src_roi.left,
src_roi.top,
src_roi.right,
src_roi.top,
src_roi.right,
src_roi.bottom,
src_roi.left,
src_roi.bottom,
];
edgefirst_gl::gl::BufferData(
edgefirst_gl::gl::ARRAY_BUFFER,
(size_of::<f32>() * 8) as isize,
(texture_vertices[(rotation_offset * 2)..]).as_ptr() as *const c_void,
edgefirst_gl::gl::DYNAMIC_DRAW,
);
let vertices_index: [u32; 4] = [0, 1, 2, 3];
edgefirst_gl::gl::DrawElements(
edgefirst_gl::gl::TRIANGLE_FAN,
vertices_index.len() as i32,
edgefirst_gl::gl::UNSIGNED_INT,
vertices_index.as_ptr() as *const c_void,
);
check_gl_error(function!(), line!())?;
Ok(())
}
}
#[allow(clippy::too_many_arguments)]
fn draw_camera_texture_eglimage(
&mut self,
src: &Tensor<u8>,
src_fmt: PixelFormat,
egl_img: PlatformHandle,
src_roi: RegionOfInterest,
mut dst_roi: RegionOfInterest,
rotation_offset: usize,
flip: Flip,
is_int8: bool,
) -> Result<(), Error> {
let src_key = BufferImportKey::from_tensor(src, src_fmt, false);
let luma_id = src_key.luma_id;
// Draw-time program selection (see draw_src_texture).
let program_id = if is_int8 {
&self.texture_int8_program_yuv
} else {
&self.texture_program_yuv
}
.as_ref()
.ok_or_else(|| {
Error::NotSupported("external-OES sampler program unavailable on this platform".into())
})?
.id;
let texture_target = edgefirst_gl::gl::TEXTURE_EXTERNAL_OES;
unsafe {
edgefirst_gl::gl::UseProgram(program_id);
edgefirst_gl::gl::ActiveTexture(edgefirst_gl::gl::TEXTURE0);
edgefirst_gl::gl::BindTexture(texture_target, self.camera_eglimage_texture.id);
super::core::set_tex_filter_clamp(texture_target, edgefirst_gl::gl::LINEAR);
// Note: GL_TEXTURE_SWIZZLE_* is not supported for
// GL_TEXTURE_EXTERNAL_OES in GLES. YUV→RGB conversion is
// handled by the driver when sampling from an external texture,
// and greyscale EGLImages replicate luma to all channels
// automatically via the YUV shader.
if self.camera_eglimage_texture.bind_egl_image_external(
&self.gl_context,
src_key,
egl_img,
)? {
check_gl_error(function!(), line!())?;
log::trace!("draw_camera: bound new src EGLImage id={luma_id:#x}");
} else {
log::trace!("draw_camera: reusing bound src EGLImage id={luma_id:#x}");
}
edgefirst_gl::gl::BindBuffer(edgefirst_gl::gl::ARRAY_BUFFER, self.vertex_buffer.id);
edgefirst_gl::gl::EnableVertexAttribArray(self.vertex_buffer.buffer_index);
match flip {
Flip::None => {}
Flip::Vertical => {
std::mem::swap(&mut dst_roi.top, &mut dst_roi.bottom);
}
Flip::Horizontal => {
std::mem::swap(&mut dst_roi.left, &mut dst_roi.right);
}
}
let camera_vertices: [f32; 12] = [
dst_roi.left,
dst_roi.top,
0., // left top
dst_roi.right,
dst_roi.top,
0., // right top
dst_roi.right,
dst_roi.bottom,
0., // right bottom
dst_roi.left,
dst_roi.bottom,
0., // left bottom
];
edgefirst_gl::gl::BufferSubData(
edgefirst_gl::gl::ARRAY_BUFFER,
0,
(size_of::<f32>() * camera_vertices.len()) as isize,
camera_vertices.as_ptr() as *const c_void,
);
edgefirst_gl::gl::BindBuffer(edgefirst_gl::gl::ARRAY_BUFFER, self.texture_buffer.id);
edgefirst_gl::gl::EnableVertexAttribArray(self.texture_buffer.buffer_index);
let texture_vertices: [f32; 16] = [
src_roi.left,
src_roi.top,
src_roi.right,
src_roi.top,
src_roi.right,
src_roi.bottom,
src_roi.left,
src_roi.bottom,
src_roi.left,
src_roi.top,
src_roi.right,
src_roi.top,
src_roi.right,
src_roi.bottom,
src_roi.left,
src_roi.bottom,
];
edgefirst_gl::gl::BufferSubData(
edgefirst_gl::gl::ARRAY_BUFFER,
0,
(size_of::<f32>() * 8) as isize,
(texture_vertices[(rotation_offset * 2)..]).as_ptr() as *const c_void,
);
let vertices_index: [u32; 4] = [0, 1, 2, 3];
edgefirst_gl::gl::DrawElements(
edgefirst_gl::gl::TRIANGLE_FAN,
vertices_index.len() as i32,
edgefirst_gl::gl::UNSIGNED_INT,
vertices_index.as_ptr() as *const c_void,
);
}
check_gl_error(function!(), line!())?;
Ok(())
}
/// `ShaderR8`: render NV12/NV16/NV24 → RGBA8 via the R8 texelFetch shader.
///
/// The combined semi-planar buffer is presented as a single-plane R8
/// `TEXTURE_2D` and the shader addresses Y and UV bytes directly,
/// parameterised by four uniforms derived from the source format.
///
/// `r8_src` selects how the R8 texture is established:
/// - `Some(egl_img)` — zero-copy EGLImage import (DMA-BUF source, the
/// `create_image_from_dma_nv_r8` path).
/// - `None` — CPU upload of the combined buffer via `glTexImage2D` (the
/// non-DMA / PBO path, e.g. orin where DMA-BUF EGLImage import is
/// unavailable). Same shader, same exact in-shader matrix.
///
/// Renders into the currently-bound FBO (the RGBA8 intermediate or the
/// DMA destination) — identical output slot to `draw_camera_texture_eglimage`.
#[allow(clippy::too_many_arguments)]
fn draw_nv_texture_2d(
&mut self,
src: &Tensor<u8>,
src_fmt: PixelFormat,
r8_src: Option<PlatformHandle>,
src_roi: RegionOfInterest,
mut dst_roi: RegionOfInterest,
rotation_offset: usize,
flip: Flip,
is_int8: bool,
) -> Result<(), Error> {
let src_w = src.width().ok_or(Error::NotAnImage)?;
let src_h = src.height().ok_or(Error::NotAnImage)?;
let tex_width = src.effective_row_stride().unwrap_or(src_w) as i32;
// Format-specific shader uniforms from the shared `chroma_layout`
// (single source of truth with the codec writer + CPU readers + macOS
// shader). `chroma_lines` (== `uv_rows_per_luma`) is the number of R8
// buffer rows each image-chroma-row occupies (NV24's CbCr row is 2W
// bytes = 2 rows; NV12/NV16 are W bytes = 1 row). The shader uses it for
// direct 2D texel addressing (no per-pixel integer divide/modulo, which
// is pathologically slow on some embedded GPUs e.g. Vivante GC7000UL).
let layout = src_fmt.chroma_layout().ok_or_else(|| {
Error::NotSupported(format!(
"draw_nv_texture_2d: unsupported format {src_fmt:?}"
))
})?;
let chroma_shift_x = layout.shift_x as i32;
let chroma_shift_y = layout.shift_y as i32;
let chroma_lines = layout.uv_rows_per_luma as i32;
let src_key = BufferImportKey::from_tensor(src, src_fmt, false);
let luma_id = src_key.luma_id;
// Draw-time program selection: the int8 NV program is the same shader
// plus the XOR-0x80 bias. Selected here for EVERY destination lowering
// (the old swap scheme only covered DMA destinations, leaving the
// heap-source int8 NV output un-biased on texture destinations).
let prog_id = if is_int8 {
self.nv_r8_int8_program.id
} else {
self.nv_r8_program.id
};
// YUV→RGB matrix + range, resolved from the source tensor's
// colorimetry (missing axes filled by the SD/HD height heuristic).
// Path B applies the matrix in-shader, so it is colorimetry-correct
// on every GPU regardless of EGL color-hint support.
let cm = crate::colorimetry::resolve_colorimetry(src.colorimetry(), src.height());
let colorimetry = (
cm.encoding
.unwrap_or(edgefirst_tensor::ColorEncoding::Bt709),
cm.range.unwrap_or(edgefirst_tensor::ColorRange::Limited),
);
let state = if is_int8 {
&mut self.nv_r8_int8_uniforms
} else {
&mut self.nv_r8_uniforms
};
let locs = state.locs;
// Uniform values persist per program: re-upload the six matrix floats
// only when this program's (encoding, range) actually changed. The
// marker is recorded AFTER the draw succeeds — an error between here
// and the upload must not leave a "already uploaded" claim for values
// that never reached the program.
let upload_colorimetry = state.last_colorimetry != Some(colorimetry);
unsafe {
edgefirst_gl::gl::UseProgram(prog_id);
edgefirst_gl::gl::ActiveTexture(edgefirst_gl::gl::TEXTURE0);
edgefirst_gl::gl::BindTexture(edgefirst_gl::gl::TEXTURE_2D, self.nv_r8_texture.id);
// NEAREST — we address by integer texel; no interpolation wanted.
super::core::set_tex_filter_clamp(
edgefirst_gl::gl::TEXTURE_2D,
edgefirst_gl::gl::NEAREST,
);
match r8_src {
Some(egl_img) => {
if self
.nv_r8_texture
.bind_egl_image(&self.gl_context, src_key, egl_img)?
{
check_gl_error(function!(), line!())?;
log::trace!("draw_nv_texture_2d: bound new R8 EGLImage id={luma_id:#x}");
} else {
log::trace!(
"draw_nv_texture_2d: reusing bound R8 EGLImage id={luma_id:#x}"
);
}
}
None => {
// Non-DMA upload path: upload the combined semi-planar buffer
// as an R8 texture (tex_width × combined_plane_height). The
// shader addresses it identically to the EGLImage case, so
// the in-shader YUV matrix is byte-for-byte the same as the
// DMA ShaderR8 path. Used where DMA-BUF EGLImage import is
// unavailable (e.g. orin) or the source is heap-backed.
//
// A PBO source MUST NOT reach here: `map()` on a PBO tensor on
// the GL thread deadlocks (the buffer is GL-owned). PBO sources
// go through `draw_src_texture_from_pbo`; guard the invariant
// locally rather than relying solely on the dispatch call graph.
if src.as_pbo().is_some() {
return Err(Error::NotSupported(
"NV R8 upload cannot map a PBO source on the GL thread; \
route PBO sources through the PBO upload path"
.into(),
));
}
let combined_h = src_fmt.combined_plane_height(src_h).ok_or_else(|| {
Error::NotSupported(format!(
"draw_nv_texture_2d upload: {src_fmt:?} is not semi-planar"
))
})?;
let offset = src.plane_offset().unwrap_or(0);
let needed = tex_width as usize * combined_h;
let map = src.map_read()?;
let bytes = map.as_slice();
if offset + needed > bytes.len() {
return Err(Error::InvalidShape(format!(
"NV R8 upload: need {needed} bytes at offset {offset} but buffer is {}",
bytes.len()
)));
}
// `UNPACK_ALIGNMENT` is 1 (set once in `new`), so any row width
// is valid — no 4-aligned-pitch requirement on the upload.
// (TODO/EDGEAI: reuse storage via glTexSubImage2D when dims are
// unchanged instead of reallocating every frame — tracked
// follow-up; needs EGLImage-vs-upload storage tracking to be safe.)
edgefirst_gl::gl::TexImage2D(
edgefirst_gl::gl::TEXTURE_2D,
0,
edgefirst_gl::gl::R8 as i32,
tex_width,
combined_h as i32,
0,
edgefirst_gl::gl::RED,
edgefirst_gl::gl::UNSIGNED_BYTE,
bytes[offset..].as_ptr() as *const c_void,
);
check_gl_error(function!(), line!())?;
// The texture now holds uploaded pixels, not an EGLImage —
// clear the EGLImage binding key so a later DMA convert rebinds.
self.nv_r8_texture.invalidate_egl_binding();
log::trace!("draw_nv_texture_2d: uploaded R8 ({tex_width}x{combined_h})");
}
}
// Per-source uniforms through link-time-cached locations (the
// `src` sampler binding is constant and uploaded at resolve time).
edgefirst_gl::gl::Uniform2i(locs.img_size, src_w as i32, src_h as i32);
edgefirst_gl::gl::Uniform1i(locs.tex_width, tex_width);
edgefirst_gl::gl::Uniform2i(locs.chroma_shift, chroma_shift_x, chroma_shift_y);
edgefirst_gl::gl::Uniform1i(locs.chroma_lines, chroma_lines);
if upload_colorimetry {
let coeffs = crate::colorimetry::yuv_to_rgb_coeffs(colorimetry.0, colorimetry.1);
edgefirst_gl::gl::Uniform1f(locs.y_offset, coeffs.y_offset);
edgefirst_gl::gl::Uniform1f(locs.y_scale, coeffs.y_scale);
edgefirst_gl::gl::Uniform1f(locs.c_vr, coeffs.c_vr);
edgefirst_gl::gl::Uniform1f(locs.c_ug, coeffs.c_ug);
edgefirst_gl::gl::Uniform1f(locs.c_vg, coeffs.c_vg);
edgefirst_gl::gl::Uniform1f(locs.c_ub, coeffs.c_ub);
}
edgefirst_gl::gl::BindBuffer(edgefirst_gl::gl::ARRAY_BUFFER, self.vertex_buffer.id);
edgefirst_gl::gl::EnableVertexAttribArray(self.vertex_buffer.buffer_index);
match flip {
Flip::None => {}
Flip::Vertical => {
std::mem::swap(&mut dst_roi.top, &mut dst_roi.bottom);
}
Flip::Horizontal => {
std::mem::swap(&mut dst_roi.left, &mut dst_roi.right);
}
}
let camera_vertices: [f32; 12] = [
dst_roi.left,
dst_roi.top,
0.,
dst_roi.right,
dst_roi.top,
0.,
dst_roi.right,
dst_roi.bottom,
0.,
dst_roi.left,
dst_roi.bottom,
0.,
];
edgefirst_gl::gl::BufferSubData(
edgefirst_gl::gl::ARRAY_BUFFER,
0,
(size_of::<f32>() * camera_vertices.len()) as isize,
camera_vertices.as_ptr() as *const c_void,
);
edgefirst_gl::gl::BindBuffer(edgefirst_gl::gl::ARRAY_BUFFER, self.texture_buffer.id);
edgefirst_gl::gl::EnableVertexAttribArray(self.texture_buffer.buffer_index);
let texture_vertices: [f32; 16] = [
src_roi.left,
src_roi.top,
src_roi.right,
src_roi.top,
src_roi.right,
src_roi.bottom,
src_roi.left,
src_roi.bottom,
src_roi.left,
src_roi.top,
src_roi.right,
src_roi.top,
src_roi.right,
src_roi.bottom,
src_roi.left,
src_roi.bottom,
];
edgefirst_gl::gl::BufferSubData(
edgefirst_gl::gl::ARRAY_BUFFER,
0,
(size_of::<f32>() * 8) as isize,
(texture_vertices[(rotation_offset * 2)..]).as_ptr() as *const c_void,
);
let vertices_index: [u32; 4] = [0, 1, 2, 3];
edgefirst_gl::gl::DrawElements(
edgefirst_gl::gl::TRIANGLE_FAN,
vertices_index.len() as i32,
edgefirst_gl::gl::UNSIGNED_INT,
vertices_index.as_ptr() as *const c_void,
);
}
check_gl_error(function!(), line!())?;
// The draw (and its colorimetry upload, when taken) succeeded — only
// now record the program's uploaded (encoding, range).
if upload_colorimetry {
let state = if is_int8 {
&mut self.nv_r8_int8_uniforms
} else {
&mut self.nv_r8_uniforms
};
state.last_colorimetry = Some(colorimetry);
}
Ok(())
}
/// Look up or create the Path-B R8 EGLImage for an NV* source tensor.
///
/// Uses a dedicated cache (`nv_r8_egl_cache`) that is keyed identically to
/// `src_egl_cache` but stores R8 imports so that the two don't interfere.
fn get_or_create_nv_r8_egl_image(
&mut self,
img: &Tensor<u8>,
img_fmt: PixelFormat,
) -> Result<PlatformHandle, crate::Error> {
// The NV R8 path imports a SOURCE (NV12/16/24 as one R8 texture), so it
// never collapses onto a destination parent import.
let id = BufferImportKey::from_tensor(img, img_fmt, false);
let luma_id = id.luma_id;
if self.nv_r8_egl_cache.sweep() {
self.nv_r8_texture.invalidate_egl_binding();
}
{
let ts = self.nv_r8_egl_cache.next_timestamp();
if let Some(cached) = self.nv_r8_egl_cache.entries.get_mut(&id) {
self.nv_r8_egl_cache.hits += 1;
cached.last_used = ts;
log::trace!("nv_r8_egl_cache hit: id={luma_id:#x}");
return Ok(Platform::import_handle(&cached.import));
}
self.nv_r8_egl_cache.misses += 1;
log::trace!("nv_r8_egl_cache miss: id={luma_id:#x}");
}
let egl_image_obj = Platform::import_buffer_nv_r8(&self.gl_context, img, img_fmt)?;
self.nv_r8_texture.invalidate_egl_binding();
let handle = Platform::import_handle(&egl_image_obj);
let guard = img.buffer_identity().weak();
if self.nv_r8_egl_cache.entries.len() >= self.nv_r8_egl_cache.capacity {
self.nv_r8_egl_cache.evict_lru();
}
let ts = self.nv_r8_egl_cache.next_timestamp();
self.nv_r8_egl_cache.entries.insert(
id,
super::cache::CachedImport {
import: egl_image_obj,
last_used: ts,
guard,
renderbuffer: None,
},
);
Ok(handle)
}
/// Look up or create an EGLImage for a DMA tensor, returning the EGL image handle.
///
/// Returns `egl::Image` (a `Copy` type wrapping `*const c_void`) to avoid borrow
/// conflicts with the caller. The cache retains ownership of the `EglImage` value;
/// the handle remains valid as long as the entry lives in the cache.
fn get_or_create_egl_image(
&mut self,
cache: CacheKind,
img: &Tensor<u8>,
img_fmt: PixelFormat,
) -> Result<PlatformHandle, crate::Error> {
// Identity + offset + geometry: sub-region views share one buffer
// identity but need distinct EGLImages (offset), and a pooled buffer
// reconfigured to a new size/format/stride needs a fresh import
// (geometry) — see BufferImportKey. Only a destination view collapses onto
// its parent key; a source view keys on its own region.
let id = BufferImportKey::from_tensor(img, img_fmt, cache == CacheKind::Dst);
let luma_id = id.luma_id;
// Sweep dead entries opportunistically before looking up.
// Invalidate texture binding state since sweep may remove a bound entry.
match cache {
CacheKind::Src => {
if self.src_egl_cache.sweep() {
self.invalidate_src_textures();
}
}
CacheKind::Dst => {
if self.dst_egl_cache.sweep() {
self.invalidate_dst_textures();
}
}
}
{
let egl_cache = match cache {
CacheKind::Src => &mut self.src_egl_cache,
CacheKind::Dst => &mut self.dst_egl_cache,
};
let ts = egl_cache.next_timestamp();
if let Some(cached) = egl_cache.entries.get_mut(&id) {
egl_cache.hits += 1;
cached.last_used = ts;
log::trace!("ImportCache {:?} hit: id={luma_id:#x}", cache);
return Ok(Platform::import_handle(&cached.import));
}
egl_cache.misses += 1;
log::trace!("ImportCache {:?} miss: id={luma_id:#x}", cache);
}
// Create the EGL image BEFORE evicting — if creation fails, we don't
// want to have destroyed a valid cache entry for nothing. Only a
// destination view imports its parent (glViewport tiling); a source view
// imports its own region (it is sampled, not rendered into).
let for_dst = cache == CacheKind::Dst;
let egl_image_obj = Platform::import_buffer(&self.gl_context, img, img_fmt, for_dst)?;
// Optionally create a GL renderbuffer backed by this EGLImage for use as an FBO
// color attachment. Renderbuffers are required on Mali/Neutron GPUs (i.MX 95)
// but are not supported on all drivers (e.g. Vivante on i.MX 8MP).
// Enabled via EDGEFIRST_OPENGL_RENDERSURFACE=1; defaults to the texture path.
let rbo = if cache == CacheKind::Dst && self.use_renderbuffer {
let mut rbo: u32 = 0;
unsafe {
edgefirst_gl::gl::GenRenderbuffers(1, &mut rbo);
edgefirst_gl::gl::BindRenderbuffer(edgefirst_gl::gl::RENDERBUFFER, rbo);
Platform::attach_renderbuffer_storage(
&self.gl_context,
Platform::import_handle(&egl_image_obj),
)?;
if let Err(e) = check_gl_error(function!(), line!()) {
edgefirst_gl::gl::DeleteRenderbuffers(1, &rbo);
return Err(e);
}
}
Some(rbo)
} else {
None
};
// Invalidate texture binding state: we're inserting a new entry and
// may evict the currently-bound one.
match cache {
CacheKind::Src => self.invalidate_src_textures(),
CacheKind::Dst => self.invalidate_dst_textures(),
}
let handle = Platform::import_handle(&egl_image_obj);
let guard = img.buffer_identity().weak();
let egl_cache = match cache {
CacheKind::Src => &mut self.src_egl_cache,
CacheKind::Dst => &mut self.dst_egl_cache,
};
// Evict least-recently-used entry if at capacity.
if egl_cache.entries.len() >= egl_cache.capacity {
egl_cache.evict_lru();
}
let ts = egl_cache.next_timestamp();
egl_cache.entries.insert(
id,
CachedImport {
import: egl_image_obj,
guard,
renderbuffer: rbo,
last_used: ts,
},
);
Ok(handle)
}
/// Look up the renderbuffer ID for a cached destination EGLImage.
fn cached_dst_renderbuffer<T>(&self, img: &Tensor<T>, fmt: PixelFormat) -> Option<u32>
where
T: num_traits::Num + Clone + std::fmt::Debug + Send + Sync,
{
let id = BufferImportKey::from_tensor(img, fmt, true);
self.dst_egl_cache
.entries
.get(&id)
.and_then(|entry| entry.renderbuffer)
}
/// Create an EGLImage from a DMA buffer with explicitly specified internal
/// dimensions and format. Used when the GL render surface differs from the
/// logical image dimensions (e.g., packed RGB reinterpretation, or the F16
/// RGBA16F-packed planar destination).
///
/// Generic over the tensor element type so it works for both `u8`
/// (packed-RGB DMA) and `f16` (RGBA16F-packed DMA) destinations. Only the
/// DMA fd, stride and offset are read from the tensor; `width`, `height`,
/// `drm_format` and `bpp` describe the GL-visible packed surface.
/// Get or create an EGLImage for a packed DMA destination with
/// reinterpreted dimensions. Uses the dst cache keyed by buffer identity.
///
/// Generic over the tensor element type so it serves both the `u8`
/// packed-RGB destination (`PackedImportFormat::Rgba8888`) and the
/// `f16` RGBA16F-packed planar destination (`Rgba16161616F`).
fn get_or_create_egl_image_rgb<T>(
&mut self,
img: &Tensor<T>,
img_fmt: PixelFormat,
width: usize,
height: usize,
packed: super::platform::PackedImportFormat,
) -> Result<PlatformHandle, crate::Error>
where
T: num_traits::Num + Clone + std::fmt::Debug + Send + Sync,
{
// Keyed identically to `cached_dst_renderbuffer` and the logical-dims
// dst path: the packed render dims derive deterministically from the
// tensor's logical geometry, so `from_tensor` is a consistent key.
let id = BufferImportKey::from_tensor(img, img_fmt, true);
if self.dst_egl_cache.sweep() {
self.invalidate_dst_textures();
}
let ts = self.dst_egl_cache.next_timestamp();
if let Some(cached) = self.dst_egl_cache.entries.get_mut(&id) {
self.dst_egl_cache.hits += 1;
cached.last_used = ts;
log::trace!("ImportCache dst (RGB) hit: id={:#x}", id.luma_id);
return Ok(Platform::import_handle(&cached.import));
}
self.dst_egl_cache.misses += 1;
log::trace!("ImportCache dst (RGB) miss: id={:#x}", id.luma_id);
// Invalidate dst texture binding state on cache miss (new EGLImage creation).
self.invalidate_dst_textures();
if self.dst_egl_cache.entries.len() >= self.dst_egl_cache.capacity {
self.dst_egl_cache.evict_lru();
}
let egl_image_obj =
Platform::import_buffer_packed(&self.gl_context, img, width, height, packed)?;
let handle = Platform::import_handle(&egl_image_obj);
let rbo = if self.use_renderbuffer {
let mut rbo: u32 = 0;
unsafe {
edgefirst_gl::gl::GenRenderbuffers(1, &mut rbo);
edgefirst_gl::gl::BindRenderbuffer(edgefirst_gl::gl::RENDERBUFFER, rbo);
Platform::attach_renderbuffer_storage(
&self.gl_context,
Platform::import_handle(&egl_image_obj),
)?;
if let Err(e) = check_gl_error(function!(), line!()) {
edgefirst_gl::gl::DeleteRenderbuffers(1, &rbo);
return Err(e);
}
}
Some(rbo)
} else {
None
};
let guard = img.buffer_identity().weak();
let ts = self.dst_egl_cache.next_timestamp();
self.dst_egl_cache.entries.insert(
id,
CachedImport {
import: egl_image_obj,
guard,
renderbuffer: rbo,
last_used: ts,
},
);
Ok(handle)
}
// Reshapes the segmentation to be compatible with RGBA texture array rendering.
fn reshape_segmentation_to_rgba(&self, segmentation: &[u8], shape: [usize; 3]) -> Vec<u8> {
let [height, width, classes] = shape;
let n_layer_stride = height * width * 4;
let n_row_stride = width * 4;
let n_col_stride = 4;
let row_stride = width * classes;
let col_stride = classes;
let mut new_segmentation = vec![0u8; n_layer_stride * classes.div_ceil(4)];
for i in 0..height {
for j in 0..width {
for k in 0..classes.div_ceil(4) * 4 {
if k >= classes {
new_segmentation[n_layer_stride * (k / 4)
+ i * n_row_stride
+ j * n_col_stride
+ k % 4] = 0;
} else {
new_segmentation[n_layer_stride * (k / 4)
+ i * n_row_stride
+ j * n_col_stride
+ k % 4] = segmentation[i * row_stride + j * col_stride + k];
}
}
}
}
new_segmentation
}
fn render_modelpack_segmentation(
&mut self,
dst_roi: RegionOfInterest,
segmentation: &[u8],
shape: [usize; 3],
) -> Result<(), crate::Error> {
log::debug!("start render_segmentation_to_image");
// TODO: Implement specialization for 2 classes and 4 classes which shouldn't
// need rearranging the data
let new_segmentation = self.reshape_segmentation_to_rgba(segmentation, shape);
let [height, width, classes] = shape;
let format = edgefirst_gl::gl::RGBA;
let texture_target = edgefirst_gl::gl::TEXTURE_2D_ARRAY;
self.segmentation_program
.load_uniform_1i(c"background_index", shape[2] as i32 - 1)?;
edgefirst_gl::use_program(self.segmentation_program.id);
edgefirst_gl::bind_texture(texture_target, self.segmentation_texture.id);
edgefirst_gl::active_texture(edgefirst_gl::gl::TEXTURE0);
edgefirst_gl::tex_parameteri(
texture_target,
edgefirst_gl::gl::TEXTURE_MIN_FILTER,
edgefirst_gl::gl::LINEAR as i32,
);
edgefirst_gl::tex_parameteri(
texture_target,
edgefirst_gl::gl::TEXTURE_MAG_FILTER,
edgefirst_gl::gl::LINEAR as i32,
);
edgefirst_gl::tex_parameteri(
texture_target,
edgefirst_gl::gl::TEXTURE_WRAP_S,
edgefirst_gl::gl::CLAMP_TO_EDGE as i32,
);
edgefirst_gl::tex_parameteri(
texture_target,
edgefirst_gl::gl::TEXTURE_WRAP_T,
edgefirst_gl::gl::CLAMP_TO_EDGE as i32,
);
edgefirst_gl::tex_image3d(
texture_target,
0,
format as i32,
width as i32,
height as i32,
classes.div_ceil(4) as i32,
0,
format,
edgefirst_gl::gl::UNSIGNED_BYTE,
Some(&new_segmentation),
);
let src_roi = RegionOfInterest {
left: 0.,
top: 1.,
right: 1.,
bottom: 0.,
};
unsafe {
edgefirst_gl::gl::BindBuffer(edgefirst_gl::gl::ARRAY_BUFFER, self.vertex_buffer.id);
edgefirst_gl::gl::EnableVertexAttribArray(self.vertex_buffer.buffer_index);
let camera_vertices: [f32; 12] = [
dst_roi.left,
dst_roi.top,
0., // left top
dst_roi.right,
dst_roi.top,
0., // right top
dst_roi.right,
dst_roi.bottom,
0., // right bottom
dst_roi.left,
dst_roi.bottom,
0., // left bottom
];
edgefirst_gl::gl::BufferSubData(
edgefirst_gl::gl::ARRAY_BUFFER,
0,
(size_of::<f32>() * camera_vertices.len()) as isize,
camera_vertices.as_ptr() as *const c_void,
);
edgefirst_gl::gl::BindBuffer(edgefirst_gl::gl::ARRAY_BUFFER, self.texture_buffer.id);
edgefirst_gl::gl::EnableVertexAttribArray(self.texture_buffer.buffer_index);
let texture_vertices: [f32; 8] = [
src_roi.left,
src_roi.top,
src_roi.right,
src_roi.top,
src_roi.right,
src_roi.bottom,
src_roi.left,
src_roi.bottom,
];
edgefirst_gl::gl::BufferSubData(
edgefirst_gl::gl::ARRAY_BUFFER,
0,
(size_of::<f32>() * 8) as isize,
(texture_vertices[0..]).as_ptr() as *const c_void,
);
let vertices_index: [u32; 4] = [0, 1, 2, 3];
edgefirst_gl::gl::DrawElements(
edgefirst_gl::gl::TRIANGLE_FAN,
vertices_index.len() as i32,
edgefirst_gl::gl::UNSIGNED_INT,
vertices_index.as_ptr() as *const c_void,
);
}
Ok(())
}
/// Bind the instanced segmentation program and configure the persistent
/// mask texture for a batch of `render_yolo_segmentation` calls.
///
/// Call once before the per-detection loop. Hoisting this out of
/// `render_yolo_segmentation` avoids N× redundant `glTexParameteri`,
/// `glUseProgram`, and `glBindTexture` calls per frame.
fn setup_yolo_segmentation_pass(&self) {
let texture_target = edgefirst_gl::gl::TEXTURE_2D;
edgefirst_gl::use_program(self.instanced_segmentation_program.id);
edgefirst_gl::active_texture(edgefirst_gl::gl::TEXTURE0);
edgefirst_gl::bind_texture(texture_target, self.segmentation_texture.id);
edgefirst_gl::tex_parameteri(
texture_target,
edgefirst_gl::gl::TEXTURE_MIN_FILTER,
edgefirst_gl::gl::LINEAR as i32,
);
edgefirst_gl::tex_parameteri(
texture_target,
edgefirst_gl::gl::TEXTURE_MAG_FILTER,
edgefirst_gl::gl::LINEAR as i32,
);
edgefirst_gl::tex_parameteri(
texture_target,
edgefirst_gl::gl::TEXTURE_WRAP_S,
edgefirst_gl::gl::CLAMP_TO_EDGE as i32,
);
edgefirst_gl::tex_parameteri(
texture_target,
edgefirst_gl::gl::TEXTURE_WRAP_T,
edgefirst_gl::gl::CLAMP_TO_EDGE as i32,
);
}
/// Render a single pre-decoded YOLO segmentation mask as a coloured
/// overlay quad. The caller must invoke [`setup_yolo_segmentation_pass`]
/// once before the first call in a batch so the program, bound texture,
/// and texture parameters are already set.
///
/// Each call uploads the mask via `glTexImage2D`, which implicitly
/// orphans the previous storage on most drivers. This avoids the
/// read-after-write hazard a persistent texture would introduce on
/// Vivante, which serialises every `glTexSubImage2D` against the still
/// in-flight previous draw and ends up slower than orphaning.
/// Compared with the original implementation we still drop the
/// per-instance CPU 1 px zero-pad copy — the shader's
/// `smoothstep(0.5, 0.65)` provides the edge antialiasing that the
/// padding used to proxy for, and texel-centre UVs keep bilinear
/// sampling strictly inside the uploaded mask region.
fn render_yolo_segmentation(
&mut self,
dst_roi: RegionOfInterest,
segmentation: &[u8],
shape: [usize; 2],
class: usize,
) -> Result<(), crate::Error> {
let [height, width] = shape;
let texture_target = edgefirst_gl::gl::TEXTURE_2D;
// Per-instance allocation + upload, equivalent to the old code path
// but without the CPU pad copy. `glTexImage2D` here implicitly
// orphans the texture's previous backing store on Vivante / Mali —
// the in-flight previous draw keeps the old storage alive while
// the new mask uploads to fresh memory, preserving CPU/GPU
// parallelism.
edgefirst_gl::tex_image2d(
texture_target,
0,
edgefirst_gl::gl::R8 as i32,
width as i32,
height as i32,
0,
edgefirst_gl::gl::RED,
edgefirst_gl::gl::UNSIGNED_BYTE,
Some(segmentation),
);
self.instanced_segmentation_program
.load_uniform_1i(c"class_index", class as i32)?;
// Texel-centre UVs: bilinear filtering returns the exact uploaded
// texel value at each corner of the quad, so no sampling reaches
// outside the mask data and no zero-padding border is needed.
let u_lo = 0.5 / width as f32;
let v_lo = 0.5 / height as f32;
let u_hi = (width as f32 - 0.5) / width as f32;
let v_hi = (height as f32 - 0.5) / height as f32;
// tc.y = 0 corresponds to mask row 0 (image top); NDC top of the quad
// (`dst_roi.top`, which holds `cvt_screen_coord(seg.ymax)`) renders
// image bottom, so the first two tex vertices get `v_hi`.
let src_roi = RegionOfInterest {
left: u_lo,
top: v_hi,
right: u_hi,
bottom: v_lo,
};
unsafe {
edgefirst_gl::gl::BindBuffer(edgefirst_gl::gl::ARRAY_BUFFER, self.vertex_buffer.id);
edgefirst_gl::gl::EnableVertexAttribArray(self.vertex_buffer.buffer_index);
let camera_vertices: [f32; 12] = [
dst_roi.left,
dst_roi.top,
0., // left top
dst_roi.right,
dst_roi.top,
0., // right top
dst_roi.right,
dst_roi.bottom,
0., // right bottom
dst_roi.left,
dst_roi.bottom,
0., // left bottom
];
edgefirst_gl::gl::BufferSubData(
edgefirst_gl::gl::ARRAY_BUFFER,
0,
(size_of::<f32>() * camera_vertices.len()) as isize,
camera_vertices.as_ptr() as *const c_void,
);
edgefirst_gl::gl::BindBuffer(edgefirst_gl::gl::ARRAY_BUFFER, self.texture_buffer.id);
edgefirst_gl::gl::EnableVertexAttribArray(self.texture_buffer.buffer_index);
let texture_vertices: [f32; 8] = [
src_roi.left,
src_roi.top,
src_roi.right,
src_roi.top,
src_roi.right,
src_roi.bottom,
src_roi.left,
src_roi.bottom,
];
edgefirst_gl::gl::BufferSubData(
edgefirst_gl::gl::ARRAY_BUFFER,
0,
(size_of::<f32>() * 8) as isize,
(texture_vertices).as_ptr() as *const c_void,
);
let vertices_index: [u32; 4] = [0, 1, 2, 3];
edgefirst_gl::gl::DrawElements(
edgefirst_gl::gl::TRIANGLE_FAN,
vertices_index.len() as i32,
edgefirst_gl::gl::UNSIGNED_INT,
vertices_index.as_ptr() as *const c_void,
);
// Vivante (i.MX 8MP GC7000UL) regresses ~2× when many masks
// queue without periodic drains: the driver appears to enter
// a slow allocation path once its command buffer or texture
// orphan queue fills. An explicit `glFinish()` per instance
// matches the legacy behaviour and keeps the per-instance
// cost bounded.
//
// Mali Valhall (i.MX 95) is the opposite — `glFinish()` here
// forces a TBDR tile store-unload of the framebuffer per
// draw, which dominates the per-instance cost. Letting the
// pipeline batch into the single `edgefirst_gl::finish()` at the end
// of `draw_decoded_masks_impl` recovers ~30% on a 40-mask
// crowd scene.
if self.is_vivante {
edgefirst_gl::gl::Finish();
}
}
Ok(())
}
/// Repack proto tensor `(H, W, num_protos)` as f32 into RGBA f16 layers
/// suitable for upload to a GL_TEXTURE_2D_ARRAY with GL_RGBA16F.
///
/// Returns `(repacked_bytes, num_layers)` where each layer is H*W*4 half-floats.
/// Render YOLO proto segmentation masks using the fused GPU pipeline.
///
/// Dispatches on the proto tensor's runtime dtype via
/// [`edgefirst_tensor::TensorDyn::dtype`]:
/// - `I8`: uploads raw int8 as `GL_R8I`, dequantizes in shader (requires
/// per-tensor [`edgefirst_tensor::Quantization`] on the proto tensor).
/// - `F32`: uploads as `GL_R32F` with hardware bilinear (if available),
/// or falls back to the `RGBA16F` repack path for older drivers.
/// - `F16`: repacks natively into `RGBA16F` without a widening step.
fn render_proto_segmentation(
&mut self,
detect: &[DetectBox],
proto_data: &ProtoData,
color_mode: crate::ColorMode,
) -> crate::Result<()> {
use edgefirst_tensor::{DType, QuantMode, TensorMapTrait, TensorTrait};
if detect.is_empty() {
return Ok(());
}
let proto_shape = proto_data.protos.shape();
if proto_shape.len() != 3 {
return Err(crate::Error::InvalidShape(format!(
"protos tensor must be rank-3, got {proto_shape:?}"
)));
}
// Interpret shape based on physical layout.
let (height, width, num_protos) = match proto_data.layout {
ProtoLayout::Nhwc => (proto_shape[0], proto_shape[1], proto_shape[2]),
ProtoLayout::Nchw => (proto_shape[1], proto_shape[2], proto_shape[0]),
};
let coeff_shape = proto_data.mask_coefficients.shape();
if coeff_shape.len() != 2 || coeff_shape[1] != num_protos {
return Err(crate::Error::InvalidShape(format!(
"mask_coefficients shape {coeff_shape:?} incompatible with protos \
{proto_shape:?} (expected [N, {num_protos}])"
)));
}
// Genuine "no detections this frame" → nothing to render.
if coeff_shape[0] == 0 {
return Ok(());
}
let texture_target = edgefirst_gl::gl::TEXTURE_2D_ARRAY;
// Pure path decision: upload strategy × program × count uniform.
// Rejects NCHW layouts and unsupported proto dtypes up front (the
// caller falls back to the CPU path on NotSupported).
let plan = super::proto_dispatch::plan_proto(
proto_data.protos.dtype(),
proto_data.layout,
self.proto_repack_compute_program.is_some(),
self.has_float_linear,
self.int8_interpolation_mode,
)?;
// The proto render's span — the path previously had none (only a
// FunctionTimer wall-clock at the draw_proto_masks entry). Plan
// fields make the chosen upload/program visible in traces.
let _span = tracing::trace_span!(
"image.draw.gl.proto",
dtype = ?proto_data.protos.dtype(),
upload = ?plan.upload,
program = ?plan.program,
num_protos,
detections = detect.len(),
)
.entered();
// Coefficient slice for the GL uniform upload path. The shaders
// consume f32 regardless of source dtype, but we hold the F32 case
// as a borrowed slice (no allocation) and only widen for F16. The
// `Cow<[f32]>` lets both arms share a single downstream pass.
//
// The F16 widening is one flat `Vec<f32>`, replacing the prior
// `Vec<Vec<f32>>` (one inner Vec per detection) — avoids N small
// heap allocations per frame on the hot path.
let mc_map_f32;
let mc_map_f16;
let mc_map_i8;
let coeff_widen_f16: Vec<f32>;
let coeff_dequant: Vec<f32>;
let coeff_slice: &[f32] = match proto_data.mask_coefficients.dtype() {
DType::F32 => {
let t = proto_data.mask_coefficients.as_f32().expect("F32");
mc_map_f32 = t.map_read()?;
mc_map_f32.as_slice()
}
DType::F16 => {
let t = proto_data.mask_coefficients.as_f16().expect("F16");
mc_map_f16 = t.map_read()?;
coeff_widen_f16 = mc_map_f16.as_slice().iter().map(|v| v.to_f32()).collect();
&coeff_widen_f16[..]
}
DType::I8 => {
let t = proto_data.mask_coefficients.as_i8().expect("I8");
mc_map_i8 = t.map_read()?;
let quant = t.quantization();
coeff_dequant = super::proto_dispatch::dequant_coeffs(
mc_map_i8.as_slice(),
quant.as_ref().map(|q| q.mode()),
"I8",
)?;
&coeff_dequant[..]
}
DType::I16 => {
let t = proto_data.mask_coefficients.as_i16().expect("I16");
let mc_map_i16 = t.map_read()?;
let quant = t.quantization();
coeff_dequant = super::proto_dispatch::dequant_coeffs(
mc_map_i16.as_slice(),
quant.as_ref().map(|q| q.mode()),
"I16",
)?;
&coeff_dequant[..]
}
other => {
return Err(crate::Error::InvalidShape(format!(
"mask_coefficients dtype {other:?} not supported on GL seg path"
)));
}
};
// Each proto-dtype arm holds its `TensorMap` for the duration of the
// GL upload and passes an `ArrayView3` borrowed from the mapped slice
// to the helper — no per-frame `to_owned()` clone of the proto tensor.
match proto_data.protos.dtype() {
DType::I8 => {
let t = proto_data.protos.as_i8().expect("I8");
let m = t.map_read()?;
let quant = t.quantization().ok_or_else(|| {
crate::Error::InvalidShape("I8 protos require quantization metadata".into())
})?;
// GL shader path: per-tensor quant only (shader uploads a
// single scale/zp uniform). Per-channel would require a
// shader rewrite — return NotSupported for now.
let (scale, zp) = match quant.mode() {
QuantMode::PerTensor { scale, zero_point } => (scale, zero_point),
QuantMode::PerTensorSymmetric { scale } => (scale, 0_i32),
QuantMode::PerChannel { axis, .. }
| QuantMode::PerChannelSymmetric { axis, .. } => {
return Err(crate::Error::NotSupported(format!(
"GL seg path: per-channel quantization (axis={axis}) \
not yet supported — falls back to CPU in caller"
)));
}
};
let protos_view = ndarray::ArrayView3::<i8>::from_shape(
(height, width, num_protos),
m.as_slice(),
)
.map_err(|e| crate::Error::InvalidShape(format!("{e}")))?;
let quantization = edgefirst_decoder::Quantization::new(scale, zp);
self.render_proto_segmentation_int8(
plan,
detect,
coeff_slice,
protos_view,
&quantization,
height,
width,
num_protos,
texture_target,
color_mode,
)?;
}
DType::F32 => {
let t = proto_data.protos.as_f32().expect("F32");
let m = t.map_read()?;
let protos_view = ndarray::ArrayView3::<f32>::from_shape(
(height, width, num_protos),
m.as_slice(),
)
.map_err(|e| crate::Error::InvalidShape(format!("{e}")))?;
self.render_proto_layers(
plan,
detect,
coeff_slice,
ProtoLayersData::F32(protos_view),
height,
width,
num_protos,
texture_target,
color_mode,
)?;
}
DType::F16 => {
let t = proto_data.protos.as_f16().expect("F16");
let m = t.map_read()?;
let protos_view = ndarray::ArrayView3::<half::f16>::from_shape(
(height, width, num_protos),
m.as_slice(),
)
.map_err(|e| crate::Error::InvalidShape(format!("{e}")))?;
self.render_proto_layers(
plan,
detect,
coeff_slice,
ProtoLayersData::F16(protos_view),
height,
width,
num_protos,
texture_target,
color_mode,
)?;
}
other => {
return Err(crate::Error::InvalidShape(format!(
"GL seg path: proto dtype {other:?} not supported"
)));
}
}
unsafe { edgefirst_gl::gl::Finish() };
Ok(())
}
/// Render detection quads using the active program. Shared by all proto
/// shader paths.
fn render_proto_detection_quads(
&self,
program: &GlProgram,
detect: &[DetectBox],
mask_coefficients: &[f32],
num_protos: usize,
color_mode: crate::ColorMode,
) -> crate::Result<()> {
let cvt_screen_coord = |normalized: f32| normalized * 2.0 - 1.0;
// Resolve the per-detection uniform locations once per program
// switch — `load_uniform_*` is a driver string lookup plus a
// redundant UseProgram, and this loop previously paid both twice
// per detection per frame. The caller has already bound `program`.
let (cached_id, mut loc_coeff, mut loc_class) = self.proto_quad_locs.get();
if cached_id != program.id {
unsafe {
loc_coeff =
edgefirst_gl::gl::GetUniformLocation(program.id, c"mask_coeff".as_ptr());
loc_class =
edgefirst_gl::gl::GetUniformLocation(program.id, c"class_index".as_ptr());
}
self.proto_quad_locs.set((program.id, loc_coeff, loc_class));
}
// Stride the flat `mask_coefficients` buffer by `num_protos` so we
// get one slice per detection. `chunks_exact` requires the total
// length to be a multiple of `num_protos`; the dispatcher already
// validates `coeff_shape == [N, num_protos]` upstream.
for (idx, (det, coeff)) in detect
.iter()
.zip(mask_coefficients.chunks_exact(num_protos))
.enumerate()
{
let color_index = color_mode.index(idx, det.label);
let mut packed_coeff = [[0.0f32; 4]; 8];
for (i, val) in coeff.iter().enumerate().take(32) {
packed_coeff[i / 4][i % 4] = *val;
}
unsafe {
edgefirst_gl::gl::Uniform4fv(loc_coeff, 8, packed_coeff.as_ptr() as *const f32);
edgefirst_gl::gl::Uniform1i(loc_class, color_index as i32);
}
let dst_roi = RegionOfInterest {
left: cvt_screen_coord(det.bbox.xmin),
top: cvt_screen_coord(det.bbox.ymax),
right: cvt_screen_coord(det.bbox.xmax),
bottom: cvt_screen_coord(det.bbox.ymin),
};
// Proto texture coords: tex row 0 = image top (data uploaded in
// row-major order where y=0 is top of image, and GL treats the
// first row of pixel data as the bottom of the texture — but
// texelFetch(y=0) returns that bottom row, which is our image top).
// So tc.y=0 → image top, tc.y=1 → image bottom.
// At NDC top (higher Y = image bottom = ymax), we want tc.y = ymax.
// At NDC bottom (lower Y = image top = ymin), we want tc.y = ymin.
let src_roi = RegionOfInterest {
left: det.bbox.xmin,
top: det.bbox.ymax,
right: det.bbox.xmax,
bottom: det.bbox.ymin,
};
unsafe {
edgefirst_gl::gl::BindBuffer(edgefirst_gl::gl::ARRAY_BUFFER, self.vertex_buffer.id);
edgefirst_gl::gl::EnableVertexAttribArray(self.vertex_buffer.buffer_index);
let camera_vertices: [f32; 12] = [
dst_roi.left,
dst_roi.top,
0.,
dst_roi.right,
dst_roi.top,
0.,
dst_roi.right,
dst_roi.bottom,
0.,
dst_roi.left,
dst_roi.bottom,
0.,
];
edgefirst_gl::gl::BufferSubData(
edgefirst_gl::gl::ARRAY_BUFFER,
0,
(size_of::<f32>() * camera_vertices.len()) as isize,
camera_vertices.as_ptr() as *const c_void,
);
edgefirst_gl::gl::BindBuffer(
edgefirst_gl::gl::ARRAY_BUFFER,
self.texture_buffer.id,
);
edgefirst_gl::gl::EnableVertexAttribArray(self.texture_buffer.buffer_index);
let texture_vertices: [f32; 8] = [
src_roi.left,
src_roi.top,
src_roi.right,
src_roi.top,
src_roi.right,
src_roi.bottom,
src_roi.left,
src_roi.bottom,
];
edgefirst_gl::gl::BufferSubData(
edgefirst_gl::gl::ARRAY_BUFFER,
0,
(size_of::<f32>() * 8) as isize,
texture_vertices.as_ptr() as *const c_void,
);
let vertices_index: [u32; 4] = [0, 1, 2, 3];
edgefirst_gl::gl::DrawElements(
edgefirst_gl::gl::TRIANGLE_FAN,
vertices_index.len() as i32,
edgefirst_gl::gl::UNSIGNED_INT,
vertices_index.as_ptr() as *const c_void,
);
}
}
Ok(())
}
/// Int8 proto path: upload raw i8 protos per `plan.upload`, render per
/// `plan.program`.
#[allow(clippy::too_many_arguments)]
fn render_proto_segmentation_int8(
&mut self,
plan: super::proto_dispatch::ProtoPlan,
detect: &[DetectBox],
mask_coefficients: &[f32],
protos: ndarray::ArrayView3<'_, i8>,
quantization: &edgefirst_decoder::Quantization,
height: usize,
width: usize,
num_protos: usize,
texture_target: u32,
color_mode: crate::ColorMode,
) -> crate::Result<()> {
// Protos are (H, W, num_protos) in row-major HWC. The GL texture
// needs layer-first CHW (one proto per layer).
if plan.upload == super::proto_dispatch::ProtoUpload::I8Compute {
let compute_program = self.proto_repack_compute_program.ok_or_else(|| {
crate::Error::InvalidShape(
"plan selected I8Compute without a compiled compute program".into(),
)
})?;
// === GLES 3.1 compute shader path ===
// Upload HWC data as-is to SSBO, let GPU transpose via compute.
// Fall through to CPU repack if proto array is non-contiguous.
let mut data = match protos.as_slice() {
Some(s) => std::borrow::Cow::Borrowed(s),
None => std::borrow::Cow::Owned(protos.iter().copied().collect()),
};
// Pad to a 4-byte boundary for SSBO int[] alignment — by copying,
// not by over-reading past the slice end.
if data.len() % 4 != 0 {
let mut owned = data.into_owned();
owned.resize(owned.len().next_multiple_of(4), 0);
data = std::borrow::Cow::Owned(owned);
}
let data_bytes = data.len();
// Allocate as R32I (imageStore-compatible; the int8 fragment
// shaders read integers identically from R8I or R32I via
// texelFetch). Immutable storage + binding handled by the gate.
if self.ensure_proto_texture(
texture_target,
edgefirst_gl::gl::R32I,
width,
height,
num_protos,
) {
Self::set_proto_tex_params(texture_target, edgefirst_gl::gl::NEAREST);
}
unsafe {
// Upload HWC data to SSBO
edgefirst_gl::gl::BindBuffer(
edgefirst_gl::gl::SHADER_STORAGE_BUFFER,
self.proto_ssbo,
);
if data_bytes > self.proto_ssbo_size {
edgefirst_gl::gl::BufferData(
edgefirst_gl::gl::SHADER_STORAGE_BUFFER,
data_bytes as isize,
data.as_ptr() as *const std::ffi::c_void,
edgefirst_gl::gl::STREAM_DRAW,
);
self.proto_ssbo_size = data_bytes;
} else {
edgefirst_gl::gl::BufferSubData(
edgefirst_gl::gl::SHADER_STORAGE_BUFFER,
0,
data_bytes as isize,
data.as_ptr() as *const std::ffi::c_void,
);
}
edgefirst_gl::gl::BindBufferBase(
edgefirst_gl::gl::SHADER_STORAGE_BUFFER,
0,
self.proto_ssbo,
);
// Bind texture as image for compute write (R32I for compatibility)
edgefirst_gl::gl::BindImageTexture(
0,
self.proto_texture.id,
0,
edgefirst_gl::gl::TRUE,
0,
edgefirst_gl::gl::WRITE_ONLY,
edgefirst_gl::gl::R32I,
);
// Dispatch compute (uniform locations resolved at compile)
edgefirst_gl::gl::UseProgram(compute_program);
let (loc_w, loc_h, loc_np) = self.proto_compute_locs;
edgefirst_gl::gl::Uniform1i(loc_w, width as i32);
edgefirst_gl::gl::Uniform1i(loc_h, height as i32);
edgefirst_gl::gl::Uniform1i(loc_np, num_protos as i32);
let groups_x = width.div_ceil(16) as u32;
let groups_y = height.div_ceil(16) as u32;
edgefirst_gl::gl::DispatchCompute(groups_x, groups_y, 1);
edgefirst_gl::gl::MemoryBarrier(
edgefirst_gl::gl::TEXTURE_FETCH_BARRIER_BIT
| edgefirst_gl::gl::SHADER_IMAGE_ACCESS_BARRIER_BIT,
);
// Unbind SSBO and log any GL errors from compute dispatch
edgefirst_gl::gl::BindBuffer(edgefirst_gl::gl::SHADER_STORAGE_BUFFER, 0);
loop {
let err = edgefirst_gl::gl::GetError();
if err == edgefirst_gl::gl::NO_ERROR {
break;
}
log::debug!("GL error after compute dispatch: 0x{err:x}");
}
}
} else {
// === GLES 3.0 fallback: CPU repack ===
let tex_data = super::proto_dispatch::repack_layers(protos);
self.upload_proto_texture(
texture_target,
edgefirst_gl::gl::R8I,
width,
height,
num_protos,
edgefirst_gl::gl::RED_INTEGER,
edgefirst_gl::gl::BYTE,
edgefirst_gl::gl::NEAREST,
&tex_data,
);
}
let proto_scale = quantization.scale;
let proto_scaled_zp = -(quantization.zero_point as f32) * quantization.scale;
match plan.program {
super::proto_dispatch::ProtoProgram::Int8Nearest
| super::proto_dispatch::ProtoProgram::Int8Bilinear => {
let program = if plan.program == super::proto_dispatch::ProtoProgram::Int8Nearest {
&self.proto_segmentation_int8_nearest_program
} else {
&self.proto_segmentation_int8_bilinear_program
};
edgefirst_gl::use_program(program.id);
program.load_uniform_1i(c"num_protos", num_protos as i32)?;
program.load_uniform_1f(c"proto_scale", proto_scale)?;
program.load_uniform_1f(c"proto_scaled_zp", proto_scaled_zp)?;
self.render_proto_detection_quads(
program,
detect,
mask_coefficients,
num_protos,
color_mode,
)?;
}
super::proto_dispatch::ProtoProgram::Int8TwoPass => {
self.render_proto_int8_two_pass(
detect,
mask_coefficients,
quantization,
height,
width,
num_protos,
texture_target,
color_mode,
)?;
}
other => {
return Err(crate::Error::InvalidShape(format!(
"proto program {other:?} is not an int8 program"
)));
}
}
Ok(())
}
/// Two-pass int8 path: dequant int8→RGBA16F FBO, then render with
/// existing f16 shader using GL_LINEAR.
#[allow(clippy::too_many_arguments)]
fn render_proto_int8_two_pass(
&mut self,
detect: &[DetectBox],
mask_coefficients: &[f32],
quantization: &edgefirst_decoder::Quantization,
height: usize,
width: usize,
num_protos: usize,
texture_target: u32,
color_mode: crate::ColorMode,
) -> crate::Result<()> {
let num_layers = num_protos.div_ceil(4);
// Save the caller's FBO and viewport so we can restore after dequant.
let (saved_fbo, saved_viewport) = unsafe {
let mut fbo: i32 = 0;
edgefirst_gl::gl::GetIntegerv(edgefirst_gl::gl::FRAMEBUFFER_BINDING, &mut fbo);
let mut vp = [0i32; 4];
edgefirst_gl::gl::GetIntegerv(edgefirst_gl::gl::VIEWPORT, vp.as_mut_ptr());
(fbo as u32, vp)
};
// Pass 1: Dequantize int8 → RGBA16F texture via the persistent
// dequant FBO. The render target is gated like the proto texture
// (recreate-on-change immutable storage) instead of a fresh
// TexImage3D per call.
if Self::ensure_immutable_tex_array(
&mut self.proto_dequant_texture,
&mut self.proto_dequant_tex_dims,
texture_target,
edgefirst_gl::gl::RGBA16F,
width,
height,
num_layers,
) {
Self::set_proto_tex_params(texture_target, edgefirst_gl::gl::LINEAR);
}
let proto_scale = quantization.scale;
let proto_scaled_zp = -(quantization.zero_point as f32) * quantization.scale;
let dequant_program = &self.proto_dequant_int8_program;
edgefirst_gl::use_program(dequant_program.id);
dequant_program.load_uniform_1f(c"proto_scale", proto_scale)?;
dequant_program.load_uniform_1f(c"proto_scaled_zp", proto_scaled_zp)?;
// Bind the int8 proto texture to TEXTURE0 for the dequant shader
edgefirst_gl::active_texture(edgefirst_gl::gl::TEXTURE0);
edgefirst_gl::bind_texture(texture_target, self.proto_texture.id);
// Render each RGBA16F layer (4 protos per layer)
for layer in 0..num_layers {
self.proto_dequant_fbo.bind();
unsafe {
edgefirst_gl::gl::FramebufferTextureLayer(
edgefirst_gl::gl::FRAMEBUFFER,
edgefirst_gl::gl::COLOR_ATTACHMENT0,
self.proto_dequant_texture.id,
0,
layer as i32,
);
edgefirst_gl::gl::Viewport(0, 0, width as i32, height as i32);
}
dequant_program.load_uniform_1i(c"base_layer", (layer * 4) as i32)?;
self.draw_fullscreen_quad()?;
}
// Restore the caller's FBO and viewport.
unsafe {
edgefirst_gl::gl::BindFramebuffer(edgefirst_gl::gl::FRAMEBUFFER, saved_fbo);
edgefirst_gl::gl::Viewport(
saved_viewport[0],
saved_viewport[1],
saved_viewport[2],
saved_viewport[3],
);
}
// Pass 2: render with existing f16 shader reading from dequant texture
let program = &self.proto_segmentation_program;
edgefirst_gl::use_program(program.id);
edgefirst_gl::active_texture(edgefirst_gl::gl::TEXTURE0);
edgefirst_gl::bind_texture(texture_target, self.proto_dequant_texture.id);
program.load_uniform_1i(c"num_layers", num_layers as i32)?;
self.render_proto_detection_quads(
program,
detect,
mask_coefficients,
num_protos,
color_mode,
)?;
Ok(())
}
/// One render for every layered-float proto plan — F32→R32F native,
/// F32→RGBA16F fallback, and native F16→RGBA16F — driven entirely by
/// the [`ProtoPlan`](super::proto_dispatch::ProtoPlan): upload strategy
/// picks the repack + texture format, `plan.program` the sampler
/// program, `plan.count_uniform` the layer-count uniform. Replaces the
/// three per-dtype `render_proto_segmentation_{f32,f16,f16_native}`
/// bodies that differed only in those three choices.
#[allow(clippy::too_many_arguments)]
fn render_proto_layers(
&mut self,
plan: super::proto_dispatch::ProtoPlan,
detect: &[DetectBox],
mask_coefficients: &[f32],
data: ProtoLayersData<'_>,
height: usize,
width: usize,
num_protos: usize,
texture_target: u32,
color_mode: crate::ColorMode,
) -> crate::Result<()> {
use super::proto_dispatch::{CountUniform, ProtoProgram, ProtoUpload};
let num_layers = num_protos.div_ceil(4);
match (plan.upload, &data) {
(ProtoUpload::F32R32f, ProtoLayersData::F32(v)) => {
// Repack protos to layer-first layout: (num_protos, H, W)
let tex_data = super::proto_dispatch::repack_layers(*v);
self.upload_proto_texture(
texture_target,
edgefirst_gl::gl::R32F,
width,
height,
num_protos,
edgefirst_gl::gl::RED,
edgefirst_gl::gl::FLOAT,
edgefirst_gl::gl::LINEAR,
&tex_data,
);
}
(ProtoUpload::F32ToRgba16f, ProtoLayersData::F32(v)) => {
let (tex_data, _) =
super::proto_dispatch::repack_rgba_f16_layers(*v, half::f16::from_f32);
self.upload_proto_texture(
texture_target,
edgefirst_gl::gl::RGBA16F,
width,
height,
num_layers,
edgefirst_gl::gl::RGBA,
edgefirst_gl::gl::HALF_FLOAT,
edgefirst_gl::gl::LINEAR,
&tex_data,
);
}
(ProtoUpload::F16Rgba16f, ProtoLayersData::F16(v)) => {
let (tex_data, _) = super::proto_dispatch::repack_rgba_f16_layers(*v, |x| x);
self.upload_proto_texture(
texture_target,
edgefirst_gl::gl::RGBA16F,
width,
height,
num_layers,
edgefirst_gl::gl::RGBA,
edgefirst_gl::gl::HALF_FLOAT,
edgefirst_gl::gl::LINEAR,
&tex_data,
);
}
(upload, _) => {
return Err(crate::Error::InvalidShape(format!(
"proto upload {upload:?} incompatible with the provided proto data"
)));
}
}
let program = match plan.program {
ProtoProgram::F32 => &self.proto_segmentation_f32_program,
ProtoProgram::F16 => &self.proto_segmentation_program,
other => {
return Err(crate::Error::InvalidShape(format!(
"proto program {other:?} is not a layered-float program"
)));
}
};
edgefirst_gl::use_program(program.id);
match plan.count_uniform {
CountUniform::NumProtos => program.load_uniform_1i(c"num_protos", num_protos as i32)?,
CountUniform::NumLayers => program.load_uniform_1i(c"num_layers", num_layers as i32)?,
}
self.render_proto_detection_quads(
program,
detect,
mask_coefficients,
num_protos,
color_mode,
)
}
fn render_segmentation(
&mut self,
detect: &[DetectBox],
segmentation: &[Segmentation],
color_mode: crate::ColorMode,
) -> crate::Result<()> {
if segmentation.is_empty() {
return Ok(());
}
let is_modelpack = segmentation[0].segmentation.shape()[2] > 1;
// top and bottom are flipped because OpenGL uses 0,0 as bottom left
let cvt_screen_coord = |normalized| normalized * 2.0 - 1.0;
if is_modelpack {
let seg = &segmentation[0];
let dst_roi = RegionOfInterest {
left: cvt_screen_coord(seg.xmin),
top: cvt_screen_coord(seg.ymax),
right: cvt_screen_coord(seg.xmax),
bottom: cvt_screen_coord(seg.ymin),
};
let segment = seg.segmentation.as_standard_layout();
let slice = segment.as_slice().ok_or(Error::Internal(
"Cannot get slice of segmentation".to_owned(),
))?;
self.render_modelpack_segmentation(
dst_roi,
slice,
[
seg.segmentation.shape()[0],
seg.segmentation.shape()[1],
seg.segmentation.shape()[2],
],
)?;
} else {
// Hoist program bind, texture bind, and texture parameter
// configuration out of the per-detection loop. These never
// change between masks, so a single setup call replaces
// ~5×N redundant GL state calls.
self.setup_yolo_segmentation_pass();
for (idx, (seg, det)) in segmentation.iter().zip(detect).enumerate() {
let color_index = color_mode.index(idx, det.label);
let dst_roi = RegionOfInterest {
left: cvt_screen_coord(seg.xmin),
top: cvt_screen_coord(seg.ymax),
right: cvt_screen_coord(seg.xmax),
bottom: cvt_screen_coord(seg.ymin),
};
let segment = seg.segmentation.as_standard_layout();
let slice = segment.as_slice().ok_or(Error::Internal(
"Cannot get slice of segmentation".to_owned(),
))?;
self.render_yolo_segmentation(
dst_roi,
slice,
[seg.segmentation.shape()[0], seg.segmentation.shape()[1]],
color_index,
)?;
}
}
edgefirst_gl::disable(edgefirst_gl::gl::BLEND);
Ok(())
}
/// Compile a GLES 3.1 compute shader program from source.
fn compile_compute_program(source: &str) -> Result<u32, Error> {
unsafe {
let cs = edgefirst_gl::gl::CreateShader(edgefirst_gl::gl::COMPUTE_SHADER);
if super::shaders::compile_shader_from_str(cs, source, "proto_repack_compute").is_err()
{
edgefirst_gl::gl::DeleteShader(cs);
return Err(Error::OpenGl("compute shader compile failed".into()));
}
let program = edgefirst_gl::gl::CreateProgram();
edgefirst_gl::gl::AttachShader(program, cs);
edgefirst_gl::gl::LinkProgram(program);
let mut linked: i32 = 0;
edgefirst_gl::gl::GetProgramiv(program, edgefirst_gl::gl::LINK_STATUS, &mut linked);
edgefirst_gl::gl::DeleteShader(cs);
if linked == 0 {
let mut log_len = 0;
edgefirst_gl::gl::GetProgramiv(
program,
edgefirst_gl::gl::INFO_LOG_LENGTH,
&mut log_len,
);
let mut log_buf: Vec<u8> = vec![0; log_len as usize];
edgefirst_gl::gl::GetProgramInfoLog(
program,
log_len,
std::ptr::null_mut(),
log_buf.as_mut_ptr() as *mut std::ffi::c_char,
);
let msg = String::from_utf8_lossy(&log_buf);
edgefirst_gl::gl::DeleteProgram(program);
return Err(Error::OpenGl(format!("compute program link failed: {msg}")));
}
Ok(program)
}
}
/// Ensure the shared proto `GL_TEXTURE_2D_ARRAY` uses immutable storage and
/// is recreated when dimensions or internal format change.
#[allow(clippy::too_many_arguments)]
/// Ensure `proto_texture` is an immutable-storage (`TexStorage3D`) array
/// of exactly `(w, h, layers, internal_fmt)`, recreating the texture
/// object on any change, and bind it on `TEXTURE0`. Returns `true` when
/// recreated (sampler params reset with the object and must be
/// re-applied by the caller).
///
/// Immutable storage is what makes the compute path's
/// `BindImageTexture` legal — ES 3.1 requires it, and `imageStore` into
/// a `TexImage3D`-allocated texture silently writes nowhere on
/// conformant drivers (Vivante and Mali both rendered garbage masks).
/// Recreate-on-change is what keeps the `(dims, internal_fmt)` gate
/// honest when renders alternate proto dtypes on one processor: the
/// previous `TexImage3D` scheme left `proto_tex_dims` stale after a
/// float upload re-allocated the shared texture, so the next int8
/// upload `TexSubImage3D`'d into an R32F allocation → GL_INVALID_VALUE
/// (0x501). Both found by the proto churn/compute regression tests.
fn ensure_proto_texture(
&mut self,
target: u32,
internal_fmt: u32,
w: usize,
h: usize,
layers: usize,
) -> bool {
Self::ensure_immutable_tex_array(
&mut self.proto_texture,
&mut self.proto_tex_dims,
target,
internal_fmt,
w,
h,
layers,
)
}
/// The shared immutable-array allocation gate behind
/// [`Self::ensure_proto_texture`] — also used by the two-pass dequant
/// target, which keeps its own texture/dims pair.
fn ensure_immutable_tex_array(
texture: &mut Texture,
tex_dims: &mut (usize, usize, usize, u32),
target: u32,
internal_fmt: u32,
w: usize,
h: usize,
layers: usize,
) -> bool {
let dims = (w, h, layers, internal_fmt);
edgefirst_gl::active_texture(edgefirst_gl::gl::TEXTURE0);
if dims == *tex_dims {
edgefirst_gl::bind_texture(target, texture.id);
return false;
}
// Immutable storage cannot be re-specified: recreate the object
// (the old one is deleted by Texture's Drop).
*texture = Texture::new();
edgefirst_gl::bind_texture(target, texture.id);
unsafe {
edgefirst_gl::gl::TexStorage3D(
target,
1,
internal_fmt,
w as i32,
h as i32,
layers as i32,
);
}
*tex_dims = dims;
true
}
/// Apply the proto texture sampler params (`filter` + CLAMP_TO_EDGE).
/// Needed (only) after [`Self::ensure_proto_texture`] recreates the
/// object; params are per-texture state.
fn set_proto_tex_params(target: u32, filter: u32) {
unsafe { super::core::set_tex_filter(target, filter) };
edgefirst_gl::tex_parameteri(
target,
edgefirst_gl::gl::TEXTURE_WRAP_S,
edgefirst_gl::gl::CLAMP_TO_EDGE as i32,
);
edgefirst_gl::tex_parameteri(
target,
edgefirst_gl::gl::TEXTURE_WRAP_T,
edgefirst_gl::gl::CLAMP_TO_EDGE as i32,
);
}
#[allow(clippy::too_many_arguments)]
fn upload_proto_texture<T: Copy>(
&mut self,
target: u32,
internal_fmt: u32,
w: usize,
h: usize,
layers: usize,
format: u32,
dtype: u32,
filter: u32,
data: &[T],
) {
if self.ensure_proto_texture(target, internal_fmt, w, h, layers) {
Self::set_proto_tex_params(target, filter);
}
unsafe {
edgefirst_gl::gl::TexSubImage3D(
target,
0,
0,
0,
0,
w as i32,
h as i32,
layers as i32,
format,
dtype,
data.as_ptr() as *const std::ffi::c_void,
);
}
}
/// Set the `opacity` uniform on all segmentation and color shader programs.
/// Skips GL calls entirely when opacity hasn't changed since the last call.
fn set_opacity_uniform(&mut self, opacity: f32) -> Result<(), Error> {
if (opacity - self.cached_opacity).abs() < f32::EPSILON {
return Ok(());
}
for program in [
&self.color_program,
&self.segmentation_program,
&self.instanced_segmentation_program,
&self.proto_segmentation_program,
&self.proto_segmentation_int8_nearest_program,
&self.proto_segmentation_int8_bilinear_program,
&self.proto_segmentation_f32_program,
] {
program.load_uniform_1f(c"opacity", opacity)?;
}
self.cached_opacity = opacity;
Ok(())
}
fn render_box(
&mut self,
dst_w: usize,
dst_h: usize,
detect: &[DetectBox],
color_mode: crate::ColorMode,
) -> Result<(), Error> {
unsafe {
edgefirst_gl::gl::UseProgram(self.color_program.id);
let rescale = |x: f32| x * 2.0 - 1.0;
let thickness = 3.0;
for (idx, d) in detect.iter().enumerate() {
let color_index = color_mode.index(idx, d.label);
self.color_program
.load_uniform_1i(c"class_index", color_index as i32)?;
edgefirst_gl::gl::BindBuffer(edgefirst_gl::gl::ARRAY_BUFFER, self.vertex_buffer.id);
edgefirst_gl::gl::EnableVertexAttribArray(self.vertex_buffer.buffer_index);
let bbox: [f32; 4] = d.bbox.into();
let outer_box = [
bbox[0] - thickness / dst_w as f32,
bbox[1] - thickness / dst_h as f32,
bbox[2] + thickness / dst_w as f32,
bbox[3] + thickness / dst_h as f32,
];
let camera_vertices: [f32; 24] = [
rescale(bbox[0]),
rescale(bbox[3]),
0., // bottom left
rescale(bbox[2]),
rescale(bbox[3]),
0., // bottom right
rescale(bbox[2]),
rescale(bbox[1]),
0., // top right
rescale(bbox[0]),
rescale(bbox[1]),
0., // top left
rescale(outer_box[0]),
rescale(outer_box[3]),
0., // bottom left
rescale(outer_box[2]),
rescale(outer_box[3]),
0., // bottom right
rescale(outer_box[2]),
rescale(outer_box[1]),
0., // top right
rescale(outer_box[0]),
rescale(outer_box[1]),
0., // top left
];
edgefirst_gl::gl::BufferData(
edgefirst_gl::gl::ARRAY_BUFFER,
(size_of::<f32>() * camera_vertices.len()) as isize,
camera_vertices.as_ptr() as *const c_void,
edgefirst_gl::gl::DYNAMIC_DRAW,
);
let vertices_index: [u32; 10] = [0, 1, 5, 2, 6, 3, 7, 0, 4, 5];
edgefirst_gl::gl::DrawElements(
edgefirst_gl::gl::TRIANGLE_STRIP,
vertices_index.len() as i32,
edgefirst_gl::gl::UNSIGNED_INT,
vertices_index.as_ptr() as *const c_void,
);
}
}
check_gl_error(function!(), line!())?;
Ok(())
}
/// Report the float render support that this processor instance should
/// advertise. Delegates to [`float_render_support`].
/// Whether the GPU is a Verisilicon/Vivante core (GL_RENDERER). Used by
/// tests to gate properties that only hold on Vivante's NV12 path (e.g. the
/// contiguous-vs-multiplane equality, which splits Path A/B off Vivante).
pub(super) fn is_vivante(&self) -> bool {
self.is_vivante
}
pub(super) fn supported_render_dtypes(&self) -> crate::RenderDtypeSupport {
float_render_support(
self.is_vivante,
self.supports_f32_color,
self.supports_f16_color,
)
}
/// Fused NV12/NV16/NV24 → PlanarRgb F16: two GPU passes under one call
/// with a **GPU-resident intermediate** — the pixel path is
/// zero-copy src → GPU → texture → GPU → zero-copy dst, never touching
/// host memory. Pass 1 renders the YUV source with the caller's full
/// geometry (resize, crop, letterbox) into the shared intermediate
/// RGBA8 texture at destination resolution (the same texture the
/// packed-RGB and Vivante planar two-passes use); pass 2 packs that
/// texture 1:1 into the RGBA16F zero-copy destination. The model-input
/// convert previously only the legacy macOS backend offered — now
/// portable (Linux DMA-BUF f16 targets included).
fn convert_nv_to_planar_float_two_pass(
&mut self,
src: &TensorDyn,
dst: &mut TensorDyn,
rotation: crate::Rotation,
flip: Flip,
crop: ResolvedCrop,
) -> crate::Result<()> {
// Parity with the float render paths: rotation/flip stay on the CPU
// fallback until the fused path grows an oracle for them (pass 1
// could render them, but untested behavior must not silently flip
// backend).
if rotation != crate::Rotation::None || flip != Flip::None {
return Err(crate::Error::NotSupported(
"GL fused NV→PlanarF16: rotation/flip not supported; using CPU fallback"
.to_string(),
));
}
let src_u8 = src.as_u8().ok_or(Error::NotAnImage)?;
let src_fmt = src.format().ok_or(Error::NotAnImage)?;
let dst_w = dst.width().ok_or(Error::NotAnImage)?;
let dst_h = dst.height().ok_or(Error::NotAnImage)?;
let _span =
tracing::trace_span!("image.convert.gl.nv_to_planar_float", dst_w, dst_h).entered();
// ── Pass 1: NV → RGBA with the caller's full geometry, into the
// shared intermediate texture (GPU-only; no tensor, no import) ──
self.ensure_packed_rgb_intermediate(dst_w, dst_h)?;
self.packed_rgb_fbo.bind();
unsafe {
edgefirst_gl::gl::FramebufferTexture2D(
edgefirst_gl::gl::FRAMEBUFFER,
edgefirst_gl::gl::COLOR_ATTACHMENT0,
edgefirst_gl::gl::TEXTURE_2D,
self.packed_rgb_intermediate_tex.id,
0,
);
check_gl_error(function!(), line!())?;
edgefirst_gl::gl::Viewport(0, 0, dst_w as i32, dst_h as i32);
}
// Pass 1 must NOT glFinish (convert_to's standalone-boundary sync):
// same-context command ordering already guarantees pass 2 samples
// the finished intermediate; the convert syncs once at pass 2's
// fence. The flag restores before `?` so an error cannot leak
// defer state.
let saved_defer = self.defer_finish;
self.defer_finish = true;
let pass1 = self.convert_to_dims(
src_u8,
src_fmt,
dst_w,
dst_h,
None,
PixelFormat::Rgba,
false,
rotation,
flip,
crop,
);
self.defer_finish = saved_defer;
pass1?;
// ── Pass 2: 1:1 pack of the intermediate into the RGBA16F
// zero-copy destination. NO crop here: pass 1 already placed the
// content band and padding at destination geometry — re-applying
// the crop would letterbox a second time (the PR #107 bug class;
// see convert_nv_to_planar_two_pass pass 2).
let (src_rect_uv, dst_rect_px, pad_color) =
super::core::float_crop_uniforms(&ResolvedCrop::no_crop(), dst_w, dst_h, dst_w, dst_h)?;
self.render_float_to_zero_copy_tail(
self.packed_rgb_intermediate_tex.id,
src_rect_uv,
dst_rect_px,
pad_color,
dst,
)
}
/// Release per-pass platform texture attachments — called by the
/// dispatch wrapper after each message whose GPU work has synced
/// (no-op while a deferred batch still owes its flush, and on
/// platforms with persistent bindings).
pub(super) fn end_gpu_pass_if_synced(&self) {
if !self.pending_flush {
Platform::end_gpu_pass(&self.gl_context);
}
}
/// Assemble the immutable capability surface for this processor.
/// Captured ONCE by the dispatch wrapper at worker startup (before its
/// message loop) — `serialize_gl` is the Vivante/galcore process-wide
/// serialization requirement; see `PlatformCaps` in `platform/mod.rs`.
pub(super) fn platform_caps(&self) -> super::platform::PlatformCaps {
super::platform::PlatformCaps {
transfer_backend: self.gl_context.transfer_backend,
render_dtypes: self.supported_render_dtypes(),
// Full per-message serialization where concurrent GL across
// contexts is unsafe: Vivante/galcore (driver races) and
// virtualized GPUs (paravirtual Metal mis-renders).
serialize_gl: self.is_vivante() || self.is_virtual_gpu,
external_oes: Platform::EXTERNAL_OES,
native_fence_sync: Platform::native_fence_sync(&self.gl_context),
}
}
}
#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
mod tests {
use super::should_reject_software_gl;
// The override env reader (`software_gl_override_enabled`) is a thin
// `var_os == "1"` wrapper; it is exercised end-to-end by the GL-init path
// on the Mesa-llvmpipe coverage lane. The decision logic below is the part
// worth pinning in a pure unit test.
#[test]
fn software_gl_rejected_by_default() {
// Software renderer, no override → reject (caller falls back to CPU).
assert!(should_reject_software_gl(true, false));
}
#[test]
fn software_gl_allowed_with_override() {
// Software renderer + override → do not reject (CI coverage path).
assert!(!should_reject_software_gl(true, true));
}
#[test]
fn hardware_gl_never_rejected() {
// A hardware renderer is never rejected, override or not.
assert!(!should_reject_software_gl(false, false));
assert!(!should_reject_software_gl(false, true));
}
// Real GL_RENDERER strings from the fleet: classification drives the
// Vivante workarounds, the software-GL rejection, and the Full
// serialization policy (Vivante + virtualized GPUs).
#[test]
fn classify_renderer_fleet_strings() {
use super::{classify_renderer, RendererTraits};
let real_gpu = RendererTraits::default();
// imx8mp (Vivante GC7000UL)
let t = classify_renderer("Vivante GC7000UL");
assert!(t.vivante && !t.software && !t.virtual_gpu);
// Apple Silicon via ANGLE (developer machines)
assert_eq!(
classify_renderer(
"ANGLE (Apple, ANGLE Metal Renderer: Apple M2 Max, \
Version 26.4.1 (Build 25E253))"
),
real_gpu
);
// Mali / V3D / Tegra: plain hardware
assert_eq!(classify_renderer("Mali-G310"), real_gpu);
assert_eq!(classify_renderer("V3D 7.1"), real_gpu);
assert_eq!(
classify_renderer("NVIDIA Tegra Orin (nvgpu)/integrated"),
real_gpu
);
// Mesa software rasterizer (CI coverage lane)
let t = classify_renderer("llvmpipe (LLVM 15.0.7, 256 bits)");
assert!(t.software && !t.vivante && !t.virtual_gpu);
// GitHub macOS runner: virtualized Metal — concurrent GL across
// contexts mis-renders there; must select the Full policy.
let t = classify_renderer(
"ANGLE (Apple, ANGLE Metal Renderer: Apple Paravirtual device, \
Version 15.7.7 (Build 24G720))",
);
assert!(t.virtual_gpu && !t.software && !t.vivante);
}
}