gpu-handle-types 0.2.0

Typed, owned native GPU resource handles (Vulkan, D3D11/12, Metal, OpenGL, CUDA, OpenCL, DMA-BUF, IOSurface, AHardwareBuffer, WebGPU, ...), cross-API sync points and video pixel formats, for passing GPU resources between libraries.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
// SPDX-License-Identifier: MIT OR Apache-2.0

//! Typed newtypes for every `GpuResource` variant payload.
//!
//! Each newtype:
//! - Owns its raw payload **privately**.
//! - Exposes a single `try_from_raw(...)` constructor that asserts the
//!   minimal invariants (non-null handles, etc.) once at construction
//!   rather than re-checking them at every importer call site.
//! - Carries either an `Arc<...>` refcount wrapper (for OS-handle /
//!   refcounted-foreign-object payloads) or `Option<Arc<dyn ResourceKeepAlive>>`
//!   (for borrowed raw handles whose lifetime is anchored by the producer).
//! - Implements `Send + Sync` on a caller-asserted contract — documented per
//!   type so each invariant is discoverable on its own.
//!
//! ## Payload types stay raw
//!
//! Although the payloads are conceptually `ash::vk::Image` etc., the
//! **actual stored types are raw** (`u64` for Vulkan handles,
//! `*mut c_void` for COM/CUDA/CL/Metal, `OwnedFd`/`OwnedHandle` for OS
//! handles wrapped in `Arc`). Pulling `ash` / `objc2` / `windows` / `ndk`
//! into this leaf crate's mandatory dep surface would force every
//! downstream crate (decoders, encoders, renderers, …) to link the
//! transitive Vulkan/COM/Apple toolchains regardless of platform.
//!
//! Typed access is offered via the opt-in `ash` feature; see the impl
//! blocks at the end of this module.
//!
//! ## Send/Sync auto-trait propagation
//!
//! The caller-asserted `unsafe impl Send + Sync` lives on each newtype,
//! not on the whole enum. The enum-level auto-derive then propagates
//! naturally — if a future variant lands a non-`Send` payload, the
//! compiler refuses to derive `Send` on `GpuResource`, forcing the author
//! to fix the payload or refactor consumers explicitly. A blanket
//! `unsafe impl Send for GpuResource` would silence exactly that
//! diagnostic.
//!
//! ## FD/handle consumer rule (CRITICAL)
//!
//! APIs that take **ownership** of the fd/handle on success MUST receive
//! a **duplicate**, never the Arc-wrapped stored handle directly.
//! Without duplication, a successful import would invalidate the fd held
//! by every surviving `Arc` clone — silent use-after-close on the next
//! clone, indistinguishable in the type system from a healthy handle.
//!
//! - **Ownership-transferring imports** (Vulkan FD/Win32 import paths,
//!   `cuImportExternalMemory` `OPAQUE_FD`, OpenCL DMA-BUF import via
//!   `cl_external_memory`): call `OwnedFd::try_clone()` /
//!   `OwnedHandle::try_clone()` and pass the dup. The `Arc` retains the
//!   original; the dup goes to the driver.
//! - **Borrowing imports** (`EGL_EXT_image_dma_buf_import`, KMS
//!   `drmModeAddFB2WithModifiers`, `drmPrimeFDToHandle`): borrow via
//!   `as_raw_fd()` directly — these APIs do not consume the fd.
//!
//! The newtype layer **cannot** enforce this — it's a per-FFI-binding
//! contract. Every per-API import call site MUST consult its API's
//! ownership wording and document the choice with a brief comment.
//!
//! ## The two ownership models
//!
//! Every `unsafe` constructor in this module falls into exactly one of
//! two models, and each names which one it is on its first doc line.
//! Their `# Safety` sections are self-contained — this section is the
//! rationale behind the clauses they all repeat, not a substitute for
//! reading them.
//!
//! ### 1. Borrowing constructors — the default
//!
//! [`VkImage`], [`D3D11Texture`], [`CudaPtr2D`], [`GlTextureHandle`],
//! [`MetalTextureHandle`], [`OpenClMem`], [`CpuBytes`] and their siblings
//! store the raw handle **verbatim and non-owningly**. None of them
//! implements [`Drop`], and none of them takes a platform reference at
//! construction: no `AddRef`, no `CFRetain`, no `clRetainMemObject`, no
//! `dup`. Dropping the last value releases, frees, closes and destroys
//! nothing — and leaks nothing either, precisely because nothing was
//! acquired. (The `keep_alive` anchor is the one thing that does run on
//! the way out, and only because it is the *caller's own* `Arc`.)
//! Consequently:
//!
//! - **The caller keeps ownership** and must still destroy the object
//!   itself when it is done, exactly as if this newtype had never been
//!   built.
//! - **The object must outlive every clone.** These types are [`Clone`],
//!   and cloning copies the raw handle's bit-pattern with no refcount
//!   bump. Destroying the underlying object while any clone survives is
//!   a use-after-free that is invisible to the borrow checker — a stale
//!   clone is indistinguishable, in the type system, from a healthy one.
//!   The `keep_alive: Option<KeepAlive>` field exists to discharge this:
//!   when it is `Some`, the [`Arc<dyn ResourceKeepAlive>`](KeepAlive)
//!   inside pins the producer's anchor for the lifetime of the newtype
//!   and every clone, and the obligation is met. When it is `None` the
//!   caller carries the obligation directly.
//! - **The object must tolerate cross-thread use.** Each type carries an
//!   `unsafe impl Send + Sync`, so a value (or clone) can be moved to and
//!   shared with the interop worker threads and the wgpu queue thread.
//!   Where an API is thread-affine, the per-type contract says so.
//!
//! ### 2. Refcount-owning constructors
//!
//! `IoSurface`, `VideoToolboxFrame` and `AHardwareBufferHandle` are
//! the exceptions (target-gated, so they render only on the matching
//! platform): each holds an `Arc` over a small wrapper
//! (`IoSurfaceRetain`, `CvBufferRetain`, `AHbInner`) whose `Drop`
//! issues exactly one `CFRelease` / `CVBufferRelease` /
//! `AHardwareBuffer_release`. Their constructors either **take a new
//! reference** (`CFRetain` / `CVBufferRetain` / `AHardwareBuffer_acquire`
//! at construction, leaving the caller's own reference untouched) or
//! **adopt the caller's** (`from_acquired`, which bumps nothing). Clone
//! is an `Arc` bump only, never a second platform retain. For these,
//! the caller must not issue the balancing release itself.
//!
//! **The refcount discharges *allocation* liveness, not *content*
//! exclusivity, and the two are independent.** A platform refcount
//! proves the object still exists; it says nothing about whether a
//! recycling producer has already handed the same object to a second
//! writer. A pooled producer must therefore *also* attach its slot
//! lease through the `keep_alive` anchor, exactly as a borrowing
//! carrier does — see [`IoSurface`]'s and [`VideoToolboxFrame`]'s
//! `# Lifetime` sections, and `WgpuTexture` (feature `wgpu`), which
//! carries the same split for the same reason. Producers that mint
//! fresh per call owe nothing and leave it `None`.
//!
//! Both Apple carriers carry the anchor because each commonly has a
//! pooled producer: an `IOSurface` export ring for `IoSurface`, a
//! `CVPixelBuffer` encoder-input pool for `VideoToolboxFrame`.
//! `AHardwareBufferHandle` is the one refcount-owning carrier without the
//! anchor, so a pooled AHB producer must pin its slot lease by other means
//! for as long as any consumer may still read the buffer.
//!
//! ### Not a third model: the typed-owned carriers
//!
//! `VkOpaqueFd`, `VkOpaqueWin32` and `DmaBufHandle` (each target-gated)
//! also own their payload — `Arc<OwnedFd>` / `Arc<OwnedHandle>`, closed
//! by libstd on the last drop — but their constructors are **safe**,
//! because `OwnedFd` / `OwnedHandle` carry that ownership in the type
//! system. They are not part of the two models above; see
//! `DmaBufHandle::new`'s *Correctness, not safety* note, and the
//! *FD/handle consumer rule* section above for why importers must dup
//! rather than hand the stored fd to an ownership-taking API.

use core::ffi::c_void;
use core::fmt;
use std::sync::Arc;

#[cfg(any(unix, target_os = "wasi", target_os = "hermit"))]
use std::os::fd::OwnedFd;

// Multi-object DMA-BUF descriptors store one `Arc<OwnedFd>` per DRM
// object; almost every real surface (single-object NV12/P010) fits the
// 2-slot inline capacity without heap-spilling.
#[cfg(any(target_os = "linux", target_os = "android"))]
use smallvec::SmallVec;

#[cfg(windows)]
use std::os::windows::io::OwnedHandle;

use crate::PixelFormat;

// ─────────────────────────────────────────────────────────────────────────────
// ResourceKeepAlive trait
// ─────────────────────────────────────────────────────────────────────────────

/// Marker trait for per-variant lifetime anchors carried on `GpuResource`
/// newtypes.
///
/// Producers attach the `Arc` they already hold (e.g. an `Arc` over an SDK
/// frame or a pool-slot guard); consumers can clone the `Arc` cheaply or
/// downcast through their own custom traits when needed.
///
/// A named trait rather than a bare `Arc<dyn Any + Send + Sync>`, so it's
/// discoverable in rustdoc and so callers can extend it.
///
/// # Consumer notification
///
/// [`Self::mark_consumed`] is invoked by the import path (for example
/// after a D3D11 keyed-mutex acquire) after the
/// consumer-side sync primitive has succeeded. Producer-side anchors
/// that carry a one-shot synchronisation state (a D3D11VA decoder's
/// keyed-mutex "consumer ack" flag; an SDK decoder's resource lock)
/// override the default no-op to suppress their fallback `Drop`-time
/// rebalance.
///
/// # Why no blanket impl
///
/// A blanket `impl<T: Send + Sync + Debug + 'static> ResourceKeepAlive
/// for T {}` would spare the common case (a keep-alive that is just an
/// `Arc<SdkFrame>`) a per-type impl, but per-type override of
/// `mark_consumed` is incompatible with that blanket — concrete types
/// covered by the blanket cannot then be special-cased without a
/// `conflicting implementations` error.
///
/// Producer-side anchors such as a D3D11VA / D3D12VA decoder's
/// plane-splitter need exactly such an override, so there is no blanket.
/// Concrete keep-alive types `impl ResourceKeepAlive for X {}`
/// explicitly — a single line for the default no-op case, an
/// override of `mark_consumed` for anchors that need it. `KeepAlive`
/// holders ([`GpuResource`](crate::GpuResource) payload fields) never call the method
/// themselves; only the import path does, after a successful strict
/// acquire.
// `MaybeSendSync` is `Send + Sync` off wasm (identical to spelling that
// bound directly) and empty on wasm, where keep-alives hold thread-affine
// `web_sys` / wgpu-on-web handles. See [`crate::MaybeSendSync`].
pub trait ResourceKeepAlive: crate::MaybeSendSync + fmt::Debug + 'static {
    /// Notification from the import path that the consumer-side sync
    /// primitive (e.g. D3D11 keyed-mutex strict `AcquireSync(1)`) has
    /// completed and the consumer's release-on-drop will close the
    /// cycle. Producer-side anchors override this to suppress their
    /// fallback `Drop`-time rebalance.
    ///
    /// Default is a no-op: anchors that don't carry sync state (the
    /// common case — most keep-alives are just `Arc<SdkFrame>` holding
    /// a refcount) ignore the call.
    fn mark_consumed(&self) {}

    /// Optional downcast hook so a type-erased [`KeepAlive`] can be
    /// resolved back to its concrete keep-alive type when a
    /// platform-specific post-drop handshake needs it. Default `None`.
    ///
    /// An Android AImage release-fence path is the motivating case: an
    /// AHB importer overrides this on its AImage-owning keep-alive and
    /// reaches the concrete type behind this erased handle to deposit the
    /// exported SYNC_FD release fence, which the AImage's `Drop` then
    /// hands to `AImage_deleteAsync` so the BufferQueue slot only returns
    /// to the producer once the GPU's reads have retired.
    fn as_any(&self) -> Option<&(dyn core::any::Any + 'static)> {
        None
    }
}

// Convenience impl for the empty-anchor placeholder. Concrete keep-
// alive types (SDK frame newtypes, decoder frame anchors, etc.) each
// `impl ResourceKeepAlive for X {}` themselves — one line for the
// default no-op, or an override of `mark_consumed`.
impl ResourceKeepAlive for () {}

/// Convenience alias for the boxed-trait-object form most call sites use.
pub type KeepAlive = Arc<dyn ResourceKeepAlive>;

// ─────────────────────────────────────────────────────────────────────────────
// InvalidHandleError
// ─────────────────────────────────────────────────────────────────────────────

/// Returned from `try_from_raw` constructors when the caller-supplied
/// payload violates an invariant the newtype enforces (e.g. a null
/// VkImage, a zero-sized D3D12 buffer).
#[derive(thiserror::Error, Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum InvalidHandleError {
    #[error("null handle: {0}")]
    NullHandle(&'static str),
    #[error("null pointer: {0}")]
    NullPointer(&'static str),
    #[error("zero size: {0}")]
    ZeroSize(&'static str),
    #[error("invalid value: {field}")]
    InvalidValue { field: &'static str },
}

// ─────────────────────────────────────────────────────────────────────────────
// Refcount-destructor wrappers (Apple / Android)
// ─────────────────────────────────────────────────────────────────────────────

// Raw CoreFoundation / CoreVideo bindings.
//
// Declared as `extern "C"` rather than going through
// `objc2-core-foundation` / `objc2-core-video` so that:
// 1. The leaf crate's Apple-target dep surface stays minimal.
// 2. The symbol names and ABI are pinned explicitly — these are stable
//    Apple framework entry points and not at risk of changing.
//
// Both are part of the CoreFoundation / CoreVideo frameworks which are
// always-linked on Apple targets via the wgpu / rustc framework search
// path; the `#[link]` attribute ensures cargo wires them in even when
// no other code references them.
#[cfg(target_vendor = "apple")]
#[link(name = "CoreFoundation", kind = "framework")]
unsafe extern "C" {
    fn CFRetain(cf: *const c_void) -> *const c_void;
    fn CFRelease(cf: *const c_void);
}

#[cfg(target_vendor = "apple")]
#[link(name = "CoreVideo", kind = "framework")]
unsafe extern "C" {
    fn CVBufferRetain(buffer: *const c_void) -> *const c_void;
    fn CVBufferRelease(buffer: *const c_void);
}

/// Apple `IOSurface` refcount-destructor wrapper. `Drop` calls
/// `CFRelease(handle)`; the *constructor* (in `IoSurface::try_from_raw`)
/// is responsible for the matching `CFRetain`.
///
/// Wrapped in `Arc` so clone is one atomic op, no extra `CFRetain` per
/// clone of the parent newtype.
#[cfg(target_vendor = "apple")]
pub struct IoSurfaceRetain {
    handle: *mut c_void,
}

#[cfg(target_vendor = "apple")]
impl IoSurfaceRetain {
    /// Take one new CoreFoundation reference to `handle`, released again
    /// by this value's [`Drop`].
    ///
    /// # Safety
    ///
    /// * `handle` must be a **non-null** pointer to a live
    ///   CoreFoundation object — an `IOSurfaceRef` at every call site in
    ///   this crate. It is passed straight to `CFRetain`, which is not
    ///   null-tolerant. Unlike `IoSurface::try_from_raw`, this
    ///   constructor performs **no** null check of its own.
    /// * The object must be live *at the moment of this call*: the
    ///   caller must still hold a reference it has not yet released.
    ///   That liveness is borrowed only for the duration of the call —
    ///   the `+1` taken here is independent, so the caller may release
    ///   its own reference immediately on return.
    /// * The caller must **not** `CFRelease` the reference created here.
    ///   Exactly one balancing `CFRelease` is issued, by `Drop`. An
    ///   extra release over-decrements the shared refcount and frees the
    ///   surface out from under every other holder, in this process and
    ///   in any other process the surface is mapped into.
    /// * No thread affinity: CoreFoundation refcounts are atomic, which
    ///   is what backs the `unsafe impl Send + Sync` below, so the
    ///   `CFRelease` may run on a thread other than this one.
    pub unsafe fn new(handle: *mut c_void) -> Self {
        // SAFETY: caller invariant.
        unsafe { CFRetain(handle) };
        Self { handle }
    }
}

#[cfg(target_vendor = "apple")]
impl Drop for IoSurfaceRetain {
    fn drop(&mut self) {
        // SAFETY: balanced with the `CFRetain` in `new`.
        unsafe { CFRelease(self.handle) };
    }
}

#[cfg(target_vendor = "apple")]
impl fmt::Debug for IoSurfaceRetain {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("IoSurfaceRetain").finish_non_exhaustive()
    }
}

// SAFETY: CoreFoundation refcounts are thread-safe; `CFRelease` from
// any thread is sound.
#[cfg(target_vendor = "apple")]
unsafe impl Send for IoSurfaceRetain {}
#[cfg(target_vendor = "apple")]
unsafe impl Sync for IoSurfaceRetain {}

/// Apple `CVPixelBuffer` (or generic `CVBuffer`) refcount-destructor
/// wrapper. `Drop` calls `CVBufferRelease(pixel_buffer)`; constructor
/// runs `CVBufferRetain`.
#[cfg(target_vendor = "apple")]
pub struct CvBufferRetain {
    pixel_buffer: *mut c_void,
}

#[cfg(target_vendor = "apple")]
impl CvBufferRetain {
    /// Take one new CoreVideo reference to `pixel_buffer`, released
    /// again by this value's [`Drop`].
    ///
    /// # Safety
    ///
    /// * `pixel_buffer` must be a **non-null** pointer to a live
    ///   `CVBufferRef`-derived object (`CVPixelBufferRef`,
    ///   `CVMetalTextureRef`, …). It is passed straight to
    ///   `CVBufferRetain`; unlike `VideoToolboxFrame::try_from_raw`,
    ///   this constructor performs **no** null check of its own.
    /// * The object must be live *at the moment of this call* — the
    ///   caller must still hold an un-released reference. That liveness
    ///   is borrowed only for the call; the `+1` taken here is
    ///   independent, so the caller may release its own reference
    ///   immediately on return.
    /// * The caller must **not** `CVBufferRelease` the reference created
    ///   here. Exactly one balancing release is issued, by `Drop`.
    /// * No thread affinity: CoreVideo refcounts are atomic, which is
    ///   what backs the `unsafe impl Send + Sync` below, so the
    ///   `CVBufferRelease` may run on a thread other than this one.
    pub unsafe fn new(pixel_buffer: *mut c_void) -> Self {
        // SAFETY: caller invariant. `CVBufferRetain` is polymorphic for
        // any CVBufferRef-derived type (`CVPixelBufferRef`,
        // `CVMetalTextureRef`, …).
        unsafe { CVBufferRetain(pixel_buffer) };
        Self { pixel_buffer }
    }
}

#[cfg(target_vendor = "apple")]
impl Drop for CvBufferRetain {
    fn drop(&mut self) {
        // SAFETY: balanced with the `CVBufferRetain` in `new`.
        unsafe { CVBufferRelease(self.pixel_buffer) };
    }
}

#[cfg(target_vendor = "apple")]
impl fmt::Debug for CvBufferRetain {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("CvBufferRetain").finish_non_exhaustive()
    }
}

// SAFETY: CoreVideo refcounts are thread-safe.
#[cfg(target_vendor = "apple")]
unsafe impl Send for CvBufferRetain {}
#[cfg(target_vendor = "apple")]
unsafe impl Sync for CvBufferRetain {}

/// Android `AHardwareBuffer*` refcount-destructor wrapper. `Drop` calls
/// `AHardwareBuffer_release(handle)`. Constructor expects the caller's
/// handle is uniquely refcounted and bumps via `AHardwareBuffer_acquire`.
#[cfg(target_os = "android")]
pub struct AHbInner {
    handle: core::ptr::NonNull<ndk_sys::AHardwareBuffer>,
}

#[cfg(target_os = "android")]
impl AHbInner {
    /// Take one new reference to `handle` via `AHardwareBuffer_acquire`,
    /// released again by this value's [`Drop`].
    ///
    /// # Safety
    ///
    /// * `handle` must point to a live `AHardwareBuffer` — one obtained
    ///   from `AHardwareBuffer_allocate`, `AImage_getHardwareBuffer`,
    ///   `AHardwareBuffer_fromHardwareBuffer`, or an equivalent NDK
    ///   entry point — and must still be live *at the moment of this
    ///   call*: the caller must hold a reference it has not released.
    ///   The pointer is passed to `AHardwareBuffer_acquire`, which does
    ///   not validate it.
    /// * Null is **not** a caller obligation: it is rejected as
    ///   [`InvalidHandleError::NullHandle`] before the acquire, and the
    ///   handle is thereafter stored as a [`core::ptr::NonNull`].
    /// * This takes a *new* reference and leaves the caller's alone. A
    ///   caller that acquired specifically to hand ownership over must
    ///   release its own reference after this returns, or use
    ///   [`Self::from_acquired`], which adopts instead of bumping.
    ///   Doing neither leaks the buffer's underlying graphics
    ///   allocation, which on Android is a shared, tightly-budgeted
    ///   gralloc resource.
    /// * The caller must **not** issue the balancing
    ///   `AHardwareBuffer_release` for the reference taken here; exactly
    ///   one is issued, by `Drop`.
    /// * No thread affinity: `AHardwareBuffer` refcounts are atomic and
    ///   the object is designed for cross-process, cross-thread sharing,
    ///   so the release may run on any thread.
    pub unsafe fn acquire(handle: *mut ndk_sys::AHardwareBuffer) -> Result<Self, InvalidHandleError> {
        let nn = core::ptr::NonNull::new(handle).ok_or(InvalidHandleError::NullHandle("AHardwareBuffer"))?;
        // SAFETY: caller invariant.
        unsafe { ndk_sys::AHardwareBuffer_acquire(handle) };
        Ok(Self { handle: nn })
    }

    /// Adopt one reference the caller already holds on `handle`. No
    /// `AHardwareBuffer_acquire` is issued; the balancing
    /// `AHardwareBuffer_release` still runs in this value's [`Drop`].
    ///
    /// # Safety
    ///
    /// * `handle` must point to a live `AHardwareBuffer` on which the
    ///   caller holds a reference that it has **not** yet released.
    /// * That reference is **transferred** here. The caller must not use
    ///   it to keep the buffer alive afterwards, and must never release
    ///   it itself — the single balancing release is issued by `Drop`,
    ///   so a caller-side release is a double free that corrupts a
    ///   refcount shared across processes.
    /// * Passing a handle the caller does **not** own a reference on
    ///   (a borrowed `AImage_getHardwareBuffer` result, say, whose
    ///   reference belongs to the `AImage`) under-counts the buffer:
    ///   `Drop` then releases a reference that was never taken. Use
    ///   [`Self::acquire`] for borrowed handles.
    /// * Null is **not** a caller obligation: it is rejected as
    ///   [`InvalidHandleError::NullHandle`].
    /// * No thread affinity, as for [`Self::acquire`].
    pub unsafe fn from_acquired(handle: *mut ndk_sys::AHardwareBuffer) -> Result<Self, InvalidHandleError> {
        let nn = core::ptr::NonNull::new(handle).ok_or(InvalidHandleError::NullHandle("AHardwareBuffer"))?;
        Ok(Self { handle: nn })
    }

    /// Borrow the raw pointer. Caller must not call `AHardwareBuffer_release`
    /// on it — the inner struct owns one refcount.
    pub fn as_ptr(&self) -> *mut ndk_sys::AHardwareBuffer {
        self.handle.as_ptr()
    }
}

#[cfg(target_os = "android")]
impl Drop for AHbInner {
    fn drop(&mut self) {
        // SAFETY: paired with the `acquire` / explicit transfer in the
        // constructor.
        unsafe { ndk_sys::AHardwareBuffer_release(self.handle.as_ptr()) };
    }
}

#[cfg(target_os = "android")]
impl fmt::Debug for AHbInner {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("AHbInner").field("handle", &self.handle.as_ptr()).finish()
    }
}

// SAFETY: AHardwareBuffer refcount ops are thread-safe per Android
// reference.
#[cfg(target_os = "android")]
unsafe impl Send for AHbInner {}
#[cfg(target_os = "android")]
unsafe impl Sync for AHbInner {}

// ─────────────────────────────────────────────────────────────────────────────
// Vulkan
// ─────────────────────────────────────────────────────────────────────────────

/// Vulkan `VkImage` on a specific `VkDevice`, with optional cross-vendor
/// identity (`deviceUUID`).
#[derive(Clone)]
pub struct VkImage {
    image: u64,
    device: *mut c_void,
    instance: *mut c_void,
    phys_dev: *mut c_void,
    uuid: Option<[u8; 16]>,
    row_pitch: u32,
    keep_alive: Option<KeepAlive>,
    /// Width in texels. `0` when unknown — the consumer's import
    /// path requires the caller to stamp this OR pass an explicit size
    /// with the import.
    width: u32,
    /// Height in texels. `0` when unknown.
    height: u32,
    /// Pixel format. `None` when unknown — the consumer's import
    /// path requires the caller to stamp this OR pass an explicit
    /// format with the import.
    format: Option<crate::PixelFormat>,
    /// Per-plane storage primitive — set for single-plane
    /// intermediates that don't map onto any `PixelFormat` variant
    /// (e.g. NV12's R8 luma / RG8 chroma planes after a decoder's
    /// shared-`VkDevice` per-plane intermediate copy). The consumer's
    /// trusted Vulkan import path resolves `wgpu::TextureFormat`
    /// from this when [`Self::format`] is `None`.
    plane_format: Option<crate::PlaneFormat>,
    /// Consumer→producer slot-release back-pressure gate. Carries
    /// the PREVIOUS frame's per-slot `Arc<AtomicU64>` + target value;
    /// the consumer's import path arms an `on_submitted_work_done`
    /// callback that stores `value` into the gate after the user's
    /// previous-frame render has retired on the wgpu queue.
    ///
    /// Mirrors the `acquire_release` field on the platform opaque-export
    /// carriers (`VkOpaqueWin32` on Windows, `VkOpaqueFd` on POSIX; the
    /// two are mutually cfg-exclusive, so neither can be linked from
    /// here) — required for any producer
    /// that recycles its destination `VkImage` across frames (e.g. a
    /// decoder's shared-`VkDevice` intermediate ring pool). Without
    /// it, the producer's next-cycle reuse of a slot CPU-spins
    /// indefinitely waiting for the never-armed gate, surfacing as
    /// a playback freeze as soon as the ring wraps.
    pub acquire_release: Option<VkSlotRelease>,
}

impl VkImage {
    /// Wrap a raw `VkImage` and its device parentage. *Borrowing*:
    /// stored non-owningly, no [`Drop`], and every obligation below
    /// extends to each [`Clone`].
    ///
    /// # Safety
    ///
    /// * `image` must be a live `VkImage` handle. It is stored verbatim
    ///   and later passed to `vkGetImageMemoryRequirements` /
    ///   `vkCmdPipelineBarrier` / `vkCmdCopyImage` by the importer, so a
    ///   handle from a destroyed image, or a handle from a *different*
    ///   Vulkan object type, is undefined behaviour. Only `image == 0`
    ///   is checked, and it is reported as
    ///   [`InvalidHandleError::NullHandle`] rather than being a caller
    ///   obligation.
    /// * `device`, when non-null, must be the `VkDevice` that `image`
    ///   was created on. `device == null` is permitted, and means
    ///   "trusted import": the consumer recovers the device implicitly,
    ///   which is sound only when it genuinely shares the device the
    ///   image was minted on. Passing null while the image lives on some
    ///   *other* device makes the importer issue commands for a handle
    ///   the device has never seen.
    /// * `instance` and `phys_dev` follow the same rule as `device`
    ///   (non-null must match, null means trusted), against the
    ///   `VkInstance` and `VkPhysicalDevice` the image's device belongs
    ///   to.
    /// * `uuid`, when `Some`, must equal `phys_dev`'s reported
    ///   `VkPhysicalDeviceIDProperties::deviceUUID`. Importers use it to
    ///   refuse cross-adapter imports; a wrong UUID defeats that check
    ///   and lets a foreign-device handle through.
    /// * `row_pitch` must be the plane-0 row pitch in bytes for a
    ///   `VK_IMAGE_TILING_LINEAR` image, or `0` for
    ///   `VK_IMAGE_TILING_OPTIMAL`. Consumers use it to size host-side
    ///   copies, so an over-large value reads past the mapping.
    /// * Lifetime: nothing here retains the image and there is no
    ///   `Drop`, so the caller must not call `vkDestroyImage` (nor free
    ///   its `VkDeviceMemory`, nor destroy `device` / `instance`) while
    ///   this value or any [`Clone`] of it is still reachable. Pass a
    ///   `keep_alive` anchor to discharge that obligation; with `None`
    ///   the caller carries it directly.
    /// * Thread affinity: none for the handle itself — `VkImage` is a
    ///   plain handle and Vulkan permits use from any thread — but the
    ///   caller must still uphold Vulkan's external-synchronisation
    ///   rules for whatever queue and command buffers the importer is
    ///   told to use.
    pub unsafe fn try_from_raw(
        image: u64,
        device: *mut c_void,
        instance: *mut c_void,
        phys_dev: *mut c_void,
        uuid: Option<[u8; 16]>,
        row_pitch: u32,
        keep_alive: Option<KeepAlive>,
    ) -> Result<Self, InvalidHandleError> {
        if image == 0 {
            return Err(InvalidHandleError::NullHandle("VkImage"));
        }
        Ok(Self {
            image,
            device,
            instance,
            phys_dev,
            uuid,
            row_pitch,
            keep_alive,
            width: 0,
            height: 0,
            format: None,
            plane_format: None,
            acquire_release: None,
        })
    }

    /// Builder-style: stamp the per-plane storage primitive. Used by
    /// producers (e.g. a shared-`VkDevice` intermediate copy) that
    /// hand the consumer a single-channel intermediate which
    /// doesn't fit any [`crate::PixelFormat`] variant.
    #[inline]
    pub fn with_plane_format(mut self, plane_format: crate::PlaneFormat) -> Self {
        self.plane_format = Some(plane_format);
        self
    }

    /// Builder-style: stamp the consumer→producer slot-release
    /// back-pressure gate. Required for ring-pool producers that
    /// recycle the underlying `VkImage` across frames — without it,
    /// the producer's next-cycle reuse of a slot CPU-spins forever
    /// waiting for the never-armed gate (visible as a playback freeze
    /// as soon as the ring wraps).
    #[inline]
    pub fn with_acquire_release(mut self, release: VkSlotRelease) -> Self {
        self.acquire_release = Some(release);
        self
    }

    /// Consumer-side accessor — mirrors `acquire_release` on the
    /// platform opaque-export carriers (`VkOpaqueWin32` / `VkOpaqueFd`,
    /// mutually cfg-exclusive). Returns `None` when the
    /// producer didn't stamp a release gate (single-shot
    /// non-ring-pool path).
    #[inline]
    pub fn acquire_release(&self) -> Option<&VkSlotRelease> {
        self.acquire_release.as_ref()
    }

    /// Builder-style: stamp the texel dimensions of the image.
    /// Required when the producer side wants the consumer's trusted-import
    /// path to know the dims without the caller having to pass an
    /// explicit size at every import site. `0` dimensions stay
    /// "unknown" — the consumer falls back to the caller's import size.
    #[inline]
    pub fn with_dimensions(mut self, width: u32, height: u32) -> Self {
        self.width = width;
        self.height = height;
        self
    }

    /// Builder-style: stamp the pixel format. See [`Self::with_dimensions`]
    /// for the rationale on producer-side stamping.
    #[inline]
    pub fn with_format(mut self, format: crate::PixelFormat) -> Self {
        self.format = Some(format);
        self
    }

    #[inline]
    pub fn image(&self) -> u64 {
        self.image
    }
    #[inline]
    pub fn device(&self) -> *mut c_void {
        self.device
    }
    #[inline]
    pub fn instance(&self) -> *mut c_void {
        self.instance
    }
    #[inline]
    pub fn phys_dev(&self) -> *mut c_void {
        self.phys_dev
    }
    #[inline]
    pub fn uuid(&self) -> Option<[u8; 16]> {
        self.uuid
    }
    #[inline]
    pub fn row_pitch(&self) -> u32 {
        self.row_pitch
    }
    #[inline]
    pub fn keep_alive(&self) -> Option<&KeepAlive> {
        self.keep_alive.as_ref()
    }
    /// `0` when unset (see [`Self::with_dimensions`]).
    #[inline]
    pub fn width(&self) -> u32 {
        self.width
    }
    /// `0` when unset (see [`Self::with_dimensions`]).
    #[inline]
    pub fn height(&self) -> u32 {
        self.height
    }
    /// `None` when unset (see [`Self::with_format`]).
    #[inline]
    pub fn format(&self) -> Option<crate::PixelFormat> {
        self.format
    }
    /// `None` when unset (see [`Self::with_plane_format`]).
    #[inline]
    pub fn plane_format(&self) -> Option<crate::PlaneFormat> {
        self.plane_format
    }
}

impl fmt::Debug for VkImage {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("VkImage")
            .field("image", &self.image)
            .field("uuid", &self.uuid)
            .field("row_pitch", &self.row_pitch)
            .finish()
    }
}

// SAFETY: Vulkan handles are thread-safe for handoff; concurrent
// mutation rules are enforced by the consumer's `vkQueueSubmit`
// sequencing.
unsafe impl Send for VkImage {}
unsafe impl Sync for VkImage {}

/// Vulkan `VkBuffer` on a specific `VkDevice`.
#[derive(Clone)]
pub struct VkBufferHandle {
    buffer: u64,
    device: *mut c_void,
    uuid: Option<[u8; 16]>,
    size: u64,
    keep_alive: Option<KeepAlive>,
}

impl VkBufferHandle {
    /// Wrap a raw `VkBuffer` and its device parentage. *Borrowing*: the
    /// handle is stored non-owningly, this type has no [`Drop`], and every
    /// obligation below extends to each [`Clone`].
    ///
    /// # Safety
    ///
    /// * `buffer` must be a live `VkBuffer` handle on `device`. As with
    ///   [`VkImage::try_from_raw`], only the zero handle is rejected
    ///   ([`InvalidHandleError::NullHandle`]); everything else is stored
    ///   verbatim and later used in `vkCmdCopyBuffer` /
    ///   `vkGetBufferMemoryRequirements` by the importer.
    /// * `device == null` is permitted and carries the same
    ///   trusted-import meaning as on [`VkImage::try_from_raw`]; when
    ///   non-null it must be the `VkDevice` `buffer` was created on.
    /// * `uuid`, when `Some`, must equal that device's physical device
    ///   `deviceUUID`, for the same cross-adapter refusal check.
    /// * `size` must not exceed the buffer's actual `VkBufferCreateInfo::size`
    ///   — importers copy `size` bytes out of it. A zero `size` is
    ///   rejected as [`InvalidHandleError::ZeroSize`] and is therefore
    ///   not a caller obligation.
    /// * Lifetime and thread affinity are exactly as for
    ///   [`VkImage::try_from_raw`]: nothing is retained, there is no
    ///   `Drop`, and `vkDestroyBuffer` must not run while this value or
    ///   any [`Clone`] of it is reachable.
    pub unsafe fn try_from_raw(
        buffer: u64,
        device: *mut c_void,
        uuid: Option<[u8; 16]>,
        size: u64,
        keep_alive: Option<KeepAlive>,
    ) -> Result<Self, InvalidHandleError> {
        if buffer == 0 {
            return Err(InvalidHandleError::NullHandle("VkBuffer"));
        }
        if size == 0 {
            return Err(InvalidHandleError::ZeroSize("VkBuffer"));
        }
        Ok(Self { buffer, device, uuid, size, keep_alive })
    }

    #[inline]
    pub fn buffer(&self) -> u64 {
        self.buffer
    }
    #[inline]
    pub fn device(&self) -> *mut c_void {
        self.device
    }
    #[inline]
    pub fn uuid(&self) -> Option<[u8; 16]> {
        self.uuid
    }
    #[inline]
    pub fn size(&self) -> u64 {
        self.size
    }
    #[inline]
    pub fn keep_alive(&self) -> Option<&KeepAlive> {
        self.keep_alive.as_ref()
    }
}

impl fmt::Debug for VkBufferHandle {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("VkBufferHandle")
            .field("buffer", &self.buffer)
            .field("uuid", &self.uuid)
            .field("size", &self.size)
            .finish()
    }
}

unsafe impl Send for VkBufferHandle {}
unsafe impl Sync for VkBufferHandle {}

/// Optional GPU-side acquire-sync attached to a `VkOpaqueFd` /
/// `VkOpaqueWin32` carrier.
///
/// When present, the consumer SHOULD chain a GPU wait on this timeline
/// at the carried `value` before any GPU read of the associated memory
/// — the producer signals `value` on the same submit that wrote the
/// memory, and skips its own CPU-side post-wait. Importer pseudocode:
///
/// ```text
/// // 1. Once per (consumer-VkDevice, handle) — cache the import:
/// let imported: vk::Semaphore =
///     vkImportSemaphoreWin32HandleKHR(.handle = timeline.handle(), TIMELINE);
///
/// // 2. Per frame — wait at `timeline.value()` on the first GPU submit
/// //    that touches the imported image.
/// ```
///
/// The carried `handle` / `fd` is stable across every frame from the
/// same producer (signal-only, one export at pool init), so importers
/// keep the imported `vk::Semaphore` cached per producer rather than
/// re-importing every frame.
///
/// `None` on a carrier means the producer guarantees CPU-visibility of
/// the memory by the time the carrier is handed over (it CPU-waits with
/// `vkWaitSemaphores` after its submit). Consumers can then
/// skip GPU sync — the read is already safe.
#[cfg(any(windows, unix, target_os = "wasi", target_os = "hermit"))]
#[derive(Clone)]
pub struct VkAcquireTimeline {
    /// OPAQUE NT-handle / fd to the producer's TIMELINE semaphore.
    /// Used by Vulkan consumers via `vkImportSemaphoreWin32HandleKHR`
    /// / `vkImportSemaphoreFdKHR`. On Linux this is also used by the
    /// OpenGL consumer via `glImportSemaphoreFdEXT` +
    /// `GL_NV_timeline_semaphore` (when the GL driver exposes it).
    #[cfg(windows)]
    handle: Arc<OwnedHandle>,
    #[cfg(any(unix, target_os = "wasi", target_os = "hermit"))]
    fd: Arc<OwnedFd>,

    /// **Windows only** — separately-exported NT handle to the **same**
    /// TIMELINE semaphore with handle type
    /// `VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D12_FENCE_BIT`. The
    /// cross-vendor `GL_EXT_semaphore_win32` extension only carries a
    /// timeline-value parameter (`GL_D3D12_FENCE_VALUE_EXT`) on the
    /// `D3D12_FENCE_EXT` handle type — `OPAQUE_WIN32` semaphores are
    /// binary-only in GL. Consumers that need a GPU-side wait on a
    /// specific timeline value (a wgpu-GL bridge, say) import this
    /// handle. `None` when the producer's Vulkan implementation
    /// didn't advertise exportable D3D12_FENCE for timeline
    /// semaphores — typical fallback is consumer-side CPU wait or
    /// producer-side CPU post-wait.
    #[cfg(windows)]
    d3d12_handle: Option<Arc<OwnedHandle>>,

    value: u64,

    /// Producer-supplied consumer-capability ack. The consumer-side
    /// import path calls [`Self::ack_wait_capability`] after it has
    /// successfully chained a GPU-side wait on this timeline (Vulkan
    /// `vkImportSemaphoreWin32HandleKHR` + submit wait, or GL
    /// `glImportSemaphoreWin32HandleEXT` + `glWaitSemaphoreEXT`).
    ///
    /// The producer reads the bool before deciding to elide its own
    /// CPU post-wait on subsequent frames — so the very first frame
    /// always pays the producer-side CPU wait (memory is guaranteed
    /// visible), and from frame 2 onwards the producer skips its
    /// post-wait only when the consumer has demonstrated it can GPU-wait.
    /// If the consumer's import fails (driver gaps — typical
    /// NVIDIA Windows GL case where `D3D12_FENCE` import + the
    /// `OPAQUE_WIN32` fallback both fail), the ack stays `false` and
    /// the producer keeps post-waiting forever — correctness preserved.
    ///
    /// `None` on a carrier means the producer wasn't going to elide
    /// anyway (a pool configured to always CPU post-wait); consumers can
    /// treat the `Option` as "don't ack — not needed".
    ack: Option<Arc<core::sync::atomic::AtomicBool>>,

    /// Producer-supplied "switch to binary fallback" request channel.
    /// Set by [`Self::signal_needs_binary_fallback`] when the consumer
    /// observes that the timeline import path is not viable on this
    /// driver — typical case: NVIDIA Windows GL, where
    /// `GL_NV_timeline_semaphore + OPAQUE_WIN32` import returns
    /// `GL_INVALID_VALUE` AND the producer's Vulkan impl reports
    /// D3D12_FENCE+TIMELINE as IMPORTABLE-only (so [`Self::d3d12_handle`]
    /// is `None`).
    ///
    /// The producer reads this bool at the start of each per-frame copy;
    /// when set, it additionally arms a per-frame fresh BINARY semaphore
    /// (created, signalled, exported, stamped via
    /// [`VkOpaqueWin32::with_acquire_binary`] / equivalent), giving the
    /// consumer a `glImportSemaphoreWin32HandleEXT` /
    /// `glWaitSemaphoreEXT` GPU-wait path that does not require the
    /// timeline extensions. The timeline export keeps flowing too — it
    /// costs nothing extra per frame and lets the bridge re-probe the
    /// timeline path opportunistically (driver updates do happen).
    ///
    /// `None` on a carrier means the producer didn't wire this
    /// fallback channel; consumers can treat the `Option` as "no
    /// binary fallback available — keep using producer CPU post-wait
    /// when timeline fails".
    needs_binary_fallback: Option<Arc<core::sync::atomic::AtomicBool>>,
}

#[cfg(any(windows, unix, target_os = "wasi", target_os = "hermit"))]
impl VkAcquireTimeline {
    /// Windows constructor — `handle` is an NT handle from
    /// `vkGetSemaphoreWin32HandleKHR` on a TIMELINE semaphore created
    /// with `VkExportSemaphoreCreateInfo.handleTypes =
    /// VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_BIT_KHR`.
    #[cfg(windows)]
    #[inline]
    pub fn new_win32(handle: Arc<OwnedHandle>, value: u64) -> Self {
        Self { handle, d3d12_handle: None, value, ack: None, needs_binary_fallback: None }
    }

    /// Unix constructor — `fd` is an fd from `vkGetSemaphoreFdKHR` on a
    /// TIMELINE semaphore created with `VkExportSemaphoreCreateInfo
    /// .handleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT_KHR`.
    #[cfg(any(unix, target_os = "wasi", target_os = "hermit"))]
    #[inline]
    pub fn new_fd(fd: Arc<OwnedFd>, value: u64) -> Self {
        Self { fd, value, ack: None, needs_binary_fallback: None }
    }

    /// Windows only — attach the D3D12_FENCE flavour of the same
    /// TIMELINE semaphore. See [`Self::d3d12_handle`] for the
    /// rationale.
    #[cfg(windows)]
    #[inline]
    pub fn with_d3d12_handle(mut self, h: Arc<OwnedHandle>) -> Self {
        self.d3d12_handle = Some(h);
        self
    }

    /// Attach the producer's consumer-capability ack bool to this
    /// carrier. The consumer calls [`Self::ack_wait_capability`] after
    /// successfully chaining a GPU wait on this timeline; the producer
    /// reads the bool on the next frame to decide whether to elide its
    /// own CPU post-wait. Never stamped (`None`) means the producer was
    /// not going to elide anyway, so a consumer may skip the ack.
    #[inline]
    pub fn with_wait_capability_ack(mut self, ack: Arc<core::sync::atomic::AtomicBool>) -> Self {
        self.ack = Some(ack);
        self
    }

    /// Called by the consumer-side import after a GPU-side wait on
    /// this timeline has been successfully chained (Vulkan submit's
    /// wait list, or GL `glWaitSemaphoreEXT` queued onto wgpu's GL
    /// command stream). Sets the producer's capability bool to `true`
    /// with release ordering so the producer's next-frame `Acquire`
    /// load observes it.
    ///
    /// Idempotent — repeated calls are cheap atomic stores.
    /// No-op when the carrier wasn't stamped with an ack (the producer
    /// wasn't planning to elide).
    #[inline]
    pub fn ack_wait_capability(&self) {
        if let Some(a) = &self.ack {
            a.store(true, core::sync::atomic::Ordering::Release);
        }
    }

    /// Exported NT handle to the producer's TIMELINE semaphore. Stable
    /// across frames (Arc-cloned per carrier; the consumer dups via
    /// `vkImportSemaphoreWin32HandleKHR`).
    #[cfg(windows)]
    #[inline]
    pub fn handle(&self) -> &Arc<OwnedHandle> {
        &self.handle
    }

    /// Windows-only D3D12_FENCE handle to the same TIMELINE semaphore
    /// (separately exported at pool init). See [`Self::with_d3d12_handle`].
    #[cfg(windows)]
    #[inline]
    pub fn d3d12_handle(&self) -> Option<&Arc<OwnedHandle>> {
        self.d3d12_handle.as_ref()
    }

    /// Exported fd to the producer's TIMELINE semaphore. Stable across
    /// frames.
    #[cfg(any(unix, target_os = "wasi", target_os = "hermit"))]
    #[inline]
    pub fn fd(&self) -> &Arc<OwnedFd> {
        &self.fd
    }

    /// Value to wait the timeline to reach before reading the
    /// associated memory. Monotonically advances per frame.
    #[inline]
    pub fn value(&self) -> u64 {
        self.value
    }

    /// Attach the producer's "switch to binary fallback" bool to this
    /// carrier. The consumer flips it via
    /// [`Self::signal_needs_binary_fallback`] when the timeline import
    /// path turns out to be unusable on this driver; the producer reads
    /// it at the start of each per-frame copy and, from then on, also arms
    /// a per-frame fresh BINARY semaphore alongside the timeline export.
    /// Never stamped (`None`) means the producer did not wire the
    /// fallback channel.
    #[inline]
    pub fn with_needs_binary_fallback_ack(mut self, ack: Arc<core::sync::atomic::AtomicBool>) -> Self {
        self.needs_binary_fallback = Some(ack);
        self
    }

    /// Called by the consumer-side import after a timeline-import
    /// attempt has failed (either the platform path is genuinely
    /// unavailable — `GL_NV_timeline_semaphore` missing,
    /// D3D12_FENCE export missing — or the import call itself
    /// returned a GL error). Flips the producer's "needs binary
    /// fallback" bool with release ordering so the producer's next
    /// per-frame copy sees it and additionally arms a per-frame
    /// fresh BINARY semaphore on the carrier.
    ///
    /// No-op when the carrier wasn't stamped with the fallback ack
    /// (the producer didn't wire the channel, typically because no
    /// consumer it targets supports binary fallback for this resource
    /// type).
    #[inline]
    pub fn signal_needs_binary_fallback(&self) {
        if let Some(a) = &self.needs_binary_fallback {
            a.store(true, core::sync::atomic::Ordering::Release);
        }
    }
}

/// Per-frame fresh BINARY semaphore carrier — the NVIDIA-Windows
/// fallback path when [`VkAcquireTimeline`] cannot be GPU-waited by
/// the consumer (no exportable D3D12_FENCE timeline flavour AND no
/// `GL_NV_timeline_semaphore + OPAQUE_WIN32` import support).
///
/// Unlike [`VkAcquireTimeline`], which exports the same long-lived
/// timeline handle once at producer-pool init and Arc-clones it onto
/// every per-frame carrier, this carrier publishes a **freshly-created
/// VkSemaphore** for each frame. The producer creates the semaphore,
/// adds it to its `vkQueueSubmit2` signal list, exports an NT handle
/// (Win32) / fd (POSIX), and stamps that handle here. The producer
/// then enqueues the underlying `VkSemaphore` onto a deferred-destroy
/// queue keyed on the per-frame timeline value, so cleanup happens
/// at the next per-frame copy after the timeline has advanced
/// past the per-frame value (i.e. after the signal has retired).
///
/// **Why per-frame fresh and not persistent?** Binary semaphores have
/// a strict pairing rule
/// ([VUID-VkSubmitInfo-pSignalSemaphores-00135]) — a binary semaphore
/// must be unsignaled at the time its signal-execution batch starts.
/// A persistent per-slot binary semaphore requires a paired waiter to
/// reset the payload between frames; under a stalled-consumer scenario
/// (consumer thread dropped a frame, didn't issue
/// `glWaitSemaphoreEXT`), the next frame's signal trips the VUID and
/// triggers `VK_ERROR_DEVICE_LOST`. Per-frame fresh sidesteps this
/// entirely, at the cost of a `vkCreateSemaphore` +
/// `vkGetSemaphoreWin32HandleKHR` + `vkDestroySemaphore` per frame.
///
/// **Why no `value` field?** Binary semaphores have a 2-state
/// payload (signaled / unsignaled) — there is no value parameter on
/// `glWaitSemaphoreEXT` for binary handles. The consumer just imports
/// the handle and queues `glWaitSemaphoreEXT(sem, ..., NULL_VALUES)`.
///
/// **Lifetime.** The producer's
/// [`std::sync::Arc<std::os::windows::io::OwnedHandle>`] /
/// [`std::sync::Arc<std::os::fd::OwnedFd>`] keeps the kernel-level NT
/// handle / fd alive until both the producer (which destroys the
/// `VkSemaphore` it minted) AND every consumer clone (which holds the
/// Arc on the carrier) have released it. The `glImportSemaphoreWin32HandleEXT`
/// / `glImportSemaphoreFdEXT` call DUPs the kernel handle internally,
/// so GL imports continue to resolve against the underlying object
/// even after the producer-side VkSemaphore is destroyed.
///
/// [VUID-VkSubmitInfo-pSignalSemaphores-00135]: https://registry.khronos.org/vulkan/specs/latest/man/html/VkSubmitInfo.html
#[cfg(any(windows, unix, target_os = "wasi", target_os = "hermit"))]
#[derive(Clone)]
pub struct VkAcquireBinary {
    /// OPAQUE NT-handle / fd to the producer's fresh per-frame BINARY
    /// semaphore. Used by GL consumers via
    /// `glImportSemaphoreWin32HandleEXT` (Windows) /
    /// `glImportSemaphoreFdEXT` (POSIX) followed by
    /// `glWaitSemaphoreEXT(sem, 0, NULL, n, textures, layouts)`.
    #[cfg(windows)]
    handle: Arc<OwnedHandle>,
    #[cfg(any(unix, target_os = "wasi", target_os = "hermit"))]
    fd: Arc<OwnedFd>,

    /// Producer-supplied consumer-capability ack — see
    /// [`VkAcquireTimeline::ack`] for the protocol. Flipped to `true`
    /// by [`Self::ack_wait_capability`] after the consumer's
    /// `glImportSemaphoreWin32HandleEXT` + `glWaitSemaphoreEXT` (or
    /// equivalent on POSIX) has succeeded. The producer reads it on
    /// the next frame to decide whether to elide its own CPU
    /// post-wait. Frame 1 always pays the post-wait (ack not yet set);
    /// frame 2+ elide once the consumer has demonstrated it can
    /// actually GPU-wait this binary handle.
    ack: Option<Arc<core::sync::atomic::AtomicBool>>,

    /// Producer-supplied "binary path went unstable" back-channel.
    /// Flipped to `true` by [`Self::signal_unstable`] when the
    /// consumer's per-frame binary import fails AFTER a prior
    /// successful import (e.g. NVIDIA Windows GL ran out of its
    /// per-process semaphore-import quota mid-stream). The producer
    /// reads this on every frame; once set, it re-engages its CPU
    /// post-wait permanently, even if [`Self::ack`] is also `true`.
    ///
    /// Without this back-channel, a producer that has stopped CPU
    /// post-waiting keeps relying on a GPU wait the consumer no longer
    /// performs, and its next reuse of the slot races the consumer's
    /// read (on NVIDIA this surfaces as `VK_ERROR_DEVICE_LOST` on the
    /// producer's next submit). The latch trades the zero-CPU-stall
    /// benefit for correctness: the per-frame BINARY mint stays, and the
    /// producer adds back its `vkWaitSemaphores` post-wait so visibility
    /// is guaranteed even when the consumer's GPU wait is a no-op.
    unstable: Option<Arc<core::sync::atomic::AtomicBool>>,
}

#[cfg(any(windows, unix, target_os = "wasi", target_os = "hermit"))]
impl VkAcquireBinary {
    /// Windows constructor — `handle` is an NT handle from
    /// `vkGetSemaphoreWin32HandleKHR` on a BINARY semaphore created
    /// with `VkExportSemaphoreCreateInfo.handleTypes =
    /// VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_BIT_KHR`.
    #[cfg(windows)]
    #[inline]
    pub fn new_win32(handle: Arc<OwnedHandle>) -> Self {
        Self { handle, ack: None, unstable: None }
    }

    /// Unix constructor — `fd` is an fd from `vkGetSemaphoreFdKHR` on
    /// a BINARY semaphore created with
    /// `VkExportSemaphoreCreateInfo.handleTypes =
    /// VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT_KHR`.
    #[cfg(any(unix, target_os = "wasi", target_os = "hermit"))]
    #[inline]
    pub fn new_fd(fd: Arc<OwnedFd>) -> Self {
        Self { fd, ack: None, unstable: None }
    }

    /// Attach the producer's consumer-capability ack bool — see
    /// [`VkAcquireTimeline::with_wait_capability_ack`].
    #[inline]
    pub fn with_wait_capability_ack(mut self, ack: Arc<core::sync::atomic::AtomicBool>) -> Self {
        self.ack = Some(ack);
        self
    }

    /// Called by the consumer after `glImportSemaphoreWin32HandleEXT` +
    /// `glWaitSemaphoreEXT` (or POSIX equivalent) has succeeded against
    /// this carrier's handle. See
    /// [`VkAcquireTimeline::ack_wait_capability`].
    #[inline]
    pub fn ack_wait_capability(&self) {
        if let Some(a) = &self.ack {
            a.store(true, core::sync::atomic::Ordering::Release);
        }
    }

    /// Attach the producer's "binary path is unstable" back-channel —
    /// the one-way latch a consumer trips via [`Self::signal_unstable`]
    /// when a per-frame binary import / wait fails after an earlier
    /// frame succeeded.
    #[inline]
    pub fn with_unstable_ack(mut self, unstable: Arc<core::sync::atomic::AtomicBool>) -> Self {
        self.unstable = Some(unstable);
        self
    }

    /// Called by the consumer when a per-frame binary import / wait
    /// fails AFTER a prior frame's success — the back-channel stamped by
    /// [`Self::with_unstable_ack`].
    /// One-way latch: once flipped, the producer permanently re-engages
    /// its CPU post-wait. Idempotent (later calls are cheap no-ops).
    #[inline]
    pub fn signal_unstable(&self) {
        if let Some(a) = &self.unstable {
            a.store(true, core::sync::atomic::Ordering::Release);
        }
    }

    /// Exported NT handle to the per-frame BINARY semaphore. Lifetime
    /// is bounded by the carrier (Arc-cloned through wrapping
    /// `GpuResource`); the consumer DUPs it via the GL import.
    #[cfg(windows)]
    #[inline]
    pub fn handle(&self) -> &Arc<OwnedHandle> {
        &self.handle
    }

    /// Exported fd to the per-frame BINARY semaphore. POSIX
    /// counterpart of `Self::handle`.
    #[cfg(any(unix, target_os = "wasi", target_os = "hermit"))]
    #[inline]
    pub fn fd(&self) -> &Arc<OwnedFd> {
        &self.fd
    }
}

#[cfg(any(windows, unix, target_os = "wasi", target_os = "hermit"))]
impl fmt::Debug for VkAcquireBinary {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        #[cfg(windows)]
        {
            f.debug_struct("VkAcquireBinary").finish_non_exhaustive()
        }
        #[cfg(any(unix, target_os = "wasi", target_os = "hermit"))]
        {
            use std::os::fd::AsRawFd;
            f.debug_struct("VkAcquireBinary").field("fd", &self.fd.as_raw_fd()).finish()
        }
    }
}

#[cfg(any(windows, unix, target_os = "wasi", target_os = "hermit"))]
impl fmt::Debug for VkAcquireTimeline {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        #[cfg(windows)]
        {
            f.debug_struct("VkAcquireTimeline")
                .field("value", &self.value)
                .field("d3d12_handle", &self.d3d12_handle.is_some())
                .finish()
        }
        #[cfg(any(unix, target_os = "wasi", target_os = "hermit"))]
        {
            use std::os::fd::AsRawFd;
            f.debug_struct("VkAcquireTimeline").field("fd", &self.fd.as_raw_fd()).field("value", &self.value).finish()
        }
    }
}

/// Consumer→producer slot-release back-pressure carrier.
///
/// Pairs a per-slot `Arc<AtomicU64>` "gate" with a `value` the consumer
/// is expected to publish into it once the consumer has finished reading
/// from the producer's slot. Used by ring-pool producers (e.g. an
/// FFmpeg-Vulkan intermediate ring, SDK exporters) to prevent
/// overwriting a slot the consumer's GPU is still sampling — without
/// this gate, a fast producer (a hardware decoder feeding a
/// high-frame-rate wgpu render loop, say) cycles back to a slot while the
/// consumer's compute / blit shader is still reading the same
/// VkDeviceMemory through its imported VkImage, triggering a
/// write-after-read hazard that surfaces as a GPU fault
/// (`VK_ERROR_DEVICE_LOST` on the producer's next `vkQueueSubmit2`).
///
/// ### Protocol
///
/// 1. Producer publishes carrier for frame `N` with slot `K`. Carrier
///    holds `VkSlotRelease { gate: G_prev, value: V_prev }` — the
///    PREVIOUS frame's gate + value, NOT this frame's.
/// 2. Consumer's import path registers a wgpu
///    `wgpu::Queue::on_submitted_work_done` callback that stores
///    `value` into `gate` (release ordering). The callback's snapshot
///    captures every queued submit up to the registration point — which
///    by usage contract includes the user's frame `N-1` render
///    submission (because the user is expected to submit each frame's
///    work between consecutive decode→import calls). The callback
///    therefore fires only after the user's frame `N-1` render has
///    retired on the GPU, at which point the slot is no longer being
///    sampled and is safe to reuse.
/// 3. Producer's pool, before reusing slot `K_prev` in frame `N+1`
///    (cycle 2 of its ring), CPU-waits for `G_prev.load(Acquire) >=
///    V_prev`. Steady-state this is a zero-cost atomic load (the
///    callback has already fired); under tail-latency or stalled-consumer
///    conditions the producer yields until the consumer
///    catches up — proper back-pressure rather than blind overwrite.
///
/// ### Why ARC, not a sender / channel?
///
/// `Arc<AtomicU64>` is the minimal primitive that satisfies the
/// requirement: lock-free store from the wgpu polling thread's callback +
/// lock-free load from the producer thread's pre-write check, with
/// release/acquire ordering establishing the necessary happens-before
/// edge. No allocation per frame, no channel-send overhead, no per-frame
/// mutex contention. Clone is one refcount bump.
///
/// ### Usage contract
///
/// This carrier is **only** meaningful when the user follows the
/// "submit each frame's render between consecutive decodes" pattern
/// (which is the standard video-playback loop). Batched / out-of-order
/// rendering would register the callback before the relevant render
/// submit, firing the gate too early and re-enabling the race.
/// Producers that publish this carrier therefore assume the standard
/// loop; mis-use would corrupt rendered output but not crash —
/// the QFOT acquire still gates per-Vulkan-spec memory visibility.
///
/// ### Lifetime
///
/// The producer owns the long-lived per-slot `Arc<AtomicU64>` (one per
/// pool slot, allocated once at pool init). Each per-frame carrier
/// clones that Arc cheaply. The consumer's `on_submitted_work_done`
/// closure captures its own Arc clone; once the closure runs (or the
/// queue is torn down with the closure unrun), the closure's Arc drops
/// and the count returns to producer-only. No cyclic ownership.
#[derive(Clone, Debug)]
pub struct VkSlotRelease {
    gate: Arc<core::sync::atomic::AtomicU64>,
    value: u64,
}

impl VkSlotRelease {
    /// Construct from a producer-owned gate Arc and the value the
    /// consumer should publish once its prior-frame render retires.
    #[inline]
    pub fn new(gate: Arc<core::sync::atomic::AtomicU64>, value: u64) -> Self {
        Self { gate, value }
    }

    /// Borrow the gate Arc (for cloning into a callback closure).
    #[inline]
    pub fn gate(&self) -> &Arc<core::sync::atomic::AtomicU64> {
        &self.gate
    }

    /// The value the consumer must store into [`Self::gate`] when its
    /// prior-frame render has retired. Producer-side reuse logic CPU-waits
    /// for `gate.load(Acquire) >= value` before overwriting the
    /// associated slot.
    #[inline]
    pub fn value(&self) -> u64 {
        self.value
    }

    /// Convenience helper for consumers that don't need a delayed
    /// `on_submitted_work_done` registration — stores `value` into
    /// `gate` with release ordering immediately.
    #[inline]
    pub fn release_now(&self) {
        self.gate.store(self.value, core::sync::atomic::Ordering::Release);
    }
}

/// The producer-side export descriptor both native opaque-handle
/// carriers carry — `VkOpaqueFd` on POSIX, `VkOpaqueWin32` on Windows.
/// (Those two are mutually-exclusive `#[cfg]`s, so they are named as
/// plain code spans here rather than intra-doc links: no single rustdoc
/// target can resolve both.)
///
/// One field per Vulkan source of truth, so a construction site reads
/// as the `vkGetMemory{Fd,Win32Handle}KHR` ceremony it mirrors:
///
/// - [`Self::size`] — `VkMemoryAllocateInfo::allocationSize`.
/// - [`Self::memory_type_index`] — `VkMemoryAllocateInfo::memoryTypeIndex`.
/// - [`Self::offset`] — the `vkBindImageMemory` bind offset.
/// - [`Self::dedicated`] — whether the allocation chained
///   `VkMemoryDedicatedAllocateInfo`.
/// - [`Self::width`] / [`Self::height`] — `VkImageCreateInfo::extent`.
/// - [`Self::format`] — the logical format behind
///   `VkImageCreateInfo::format`.
/// - [`Self::uuid`] — `VkPhysicalDeviceIDProperties::deviceUUID`.
///
/// # Why plain `pub` fields
///
/// The descriptor is inert metadata: the importer reads every field
/// back verbatim to reconstruct a matching `VkImageCreateInfo` +
/// `VkMemoryDedicatedAllocateInfo` chain. The invariants that *can* be
/// checked without a live `VkDevice` (non-zero `size`, non-degenerate
/// extent) are checked by the carrier constructors — which are the only
/// way to build a carrier — and each carrier then stores its descriptor
/// **privately**, exposing it only through by-value accessors. A
/// validated carrier therefore cannot be edited back into an invalid
/// one; the mutability stops at the constructor boundary.
#[cfg(any(unix, target_os = "wasi", target_os = "hermit", windows))]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct VkOpaqueExportDesc {
    /// `VkMemoryAllocateInfo::allocationSize` of the exported
    /// `VkDeviceMemory`. Rejected when zero.
    pub size: u64,
    /// `VkMemoryAllocateInfo::memoryTypeIndex` of the exported
    /// `VkDeviceMemory` — **on the exporting physical device**, which
    /// for an opaque payload is by construction the importer's own (the
    /// handle is only meaningful on the device whose [`Self::uuid`] this
    /// is).
    ///
    /// # Why this is not optional, and why the importer must not
    /// re-derive it
    ///
    /// For a payload *created by the Vulkan API* and carried over an
    /// opaque handle type, the import-side allocation must repeat the
    /// producer's numbers exactly:
    ///
    /// * `VUID-VkMemoryAllocateInfo-allocationSize-01742`
    ///   (`VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT`) and
    /// * `VUID-VkMemoryAllocateInfo-allocationSize-01743`
    ///   (`..._OPAQUE_WIN32_BIT` / `..._OPAQUE_WIN32_KMT_BIT`)
    ///
    /// both read: *"the values of `allocationSize` and
    /// `memoryTypeIndex` **must** match those specified when the payload
    /// being imported was created"*. Sharing a physical device and
    /// intersecting `memoryTypeBits` do **not** relax that — an importer
    /// that re-runs its own "first device-local type" search can legally
    /// land on a different index than a producer that preferred, say,
    /// non-host-visible device-local memory, and the two disagree
    /// silently.
    ///
    /// The importer also cannot recover the value from the driver:
    /// `vkGetMemoryWin32HandlePropertiesKHR` /
    /// `vkGetMemoryFdPropertiesKHR` are *forbidden* for opaque handle
    /// types (`VUID-vkGetMemoryWin32HandlePropertiesKHR-handleType-00666`,
    /// `VUID-vkGetMemoryFdPropertiesKHR-handleType-00674`). Carrying it
    /// on the descriptor is therefore the only correct channel.
    ///
    /// A consumer should still validate what it receives — the index
    /// must be `< VkPhysicalDeviceMemoryProperties::memoryTypeCount` and
    /// must be set in its own image's `memoryTypeBits` — and fall back
    /// rather than allocate when it is not.
    pub memory_type_index: u32,
    /// Byte offset of the image inside the exported allocation — the
    /// `memoryOffset` the producer passed to `vkBindImageMemory`. `0`
    /// for the common single-image dedicated bind.
    pub offset: u64,
    /// Mirrors `VkMemoryDedicatedAllocateInfo` — the importer MUST chain
    /// the matching `VkMemoryDedicatedAllocateInfo` if this is `true`.
    pub dedicated: bool,
    /// `VkImageCreateInfo::extent.width`. Rejected when zero.
    pub width: u32,
    /// `VkImageCreateInfo::extent.height`. Rejected when zero.
    pub height: u32,
    /// Logical format of the exported image. Single-plane exports of a
    /// multi-plane surface additionally stamp
    /// `with_plane_format(..)` on the carrier.
    pub format: PixelFormat,
    /// Source physical-device `deviceUUID`
    /// (`VkPhysicalDeviceIDProperties::deviceUUID`). The receiver's
    /// `VkPhysicalDevice` MUST report the same UUID — opaque
    /// fd / NT-handle export is same-physical-device-only.
    pub uuid: [u8; 16],
}

/// Vulkan opaque-fd export via `VK_KHR_external_memory_fd`.
///
/// `fd` is `Arc<OwnedFd>` — Clone bumps the Arc; last drop closes the
/// fd via std's `OwnedFd::drop`. Producers handing this off to an
/// **ownership-transferring** importer (`vkAllocateMemory` with
/// `VkImportMemoryFdInfoKHR`, `cuImportExternalMemory` with `OPAQUE_FD`)
/// MUST call `OwnedFd::try_clone()` and pass the dup — see the
/// module-level "FD/handle consumer rule".
#[cfg(any(unix, target_os = "wasi", target_os = "hermit"))]
#[derive(Clone)]
pub struct VkOpaqueFd {
    fd: Arc<OwnedFd>,
    /// Validated at construction, never re-exposed mutably — see
    /// [`VkOpaqueExportDesc`]. Read back field-by-field through
    /// [`Self::size`], [`Self::offset`], … or whole via `Self::desc`.
    desc: VkOpaqueExportDesc,
    /// Per-plane storage format hint. `Some(R8)` / `Some(RG8)` / etc.
    /// override `format`'s implied layout when the carrier is publishing
    /// a SINGLE plane (e.g. NV12 Y or UV) rather than a full multi-plane
    /// surface. The consumer-side importer prefers `plane_format` over
    /// `format` when present — required for FFmpeg-Vulkan producers that
    /// set `AV_VK_FRAME_FLAG_DISABLE_MULTIPLANE`, exporting each plane as
    /// its own dedicated `VkDeviceMemory` + `OPAQUE_FD` handle.
    plane_format: Option<crate::PlaneFormat>,
    /// `VkImageUsageFlags` the producer used when creating the source
    /// `VkImage`. **Critical for cross-device OPAQUE imports**: per
    /// VK_KHR_external_memory_fd § "External Resource Sharing", the
    /// consumer-side `VkImageCreateInfo` MUST match the producer's
    /// exactly (modulo `pNext`), and `usage` participates in the
    /// driver's tile-layout / compression-metadata choice (notably
    /// NVIDIA's Delta Color Compression). A mismatch produces visible
    /// corruption on the consumer side — horizontal stripes on
    /// shareable-memory GL imports, progressive misreads on
    /// Vulkan-Vulkan imports that surface as DEVICE_LOST after the
    /// driver detects inconsistent state. `None` means the producer
    /// didn't publish its usage — the consumer falls back to deriving
    /// Vulkan usage flags from the wgpu usages it requested for the
    /// import (correct for D3D11/D3D12 sources where there's no
    /// Vulkan-side usage to mirror).
    vk_image_usage: Option<u32>,
    /// Producer-side acquire-sync timeline — see [`VkAcquireTimeline`].
    /// When `Some`, the consumer SHOULD chain a GPU wait on the carried
    /// timeline at `value()` before its first GPU read; the producer
    /// skips its own CPU post-wait when stamping this. When `None`,
    /// memory is already CPU-visible.
    acquire_timeline: Option<VkAcquireTimeline>,
    /// Producer-side acquire-sync BINARY semaphore — see
    /// [`VkAcquireBinary`]. Co-exists with [`Self::acquire_timeline`]:
    /// the producer arms BOTH whenever the timeline carrier's
    /// `needs_binary_fallback` ack has been flipped, giving the
    /// consumer two GPU-wait paths to try (timeline first when
    /// supported, binary as the cross-vendor fallback). Either
    /// successful wait elides the producer's CPU post-wait on
    /// subsequent frames via the carrier's ack channel.
    acquire_binary: Option<VkAcquireBinary>,
    /// Consumer→producer slot-release back-pressure carrier — see
    /// [`VkSlotRelease`] field docs. Producers that recycle the same
    /// `VkDeviceMemory` across frames (ring pools) stamp this so the
    /// consumer's `on_submitted_work_done` can signal "prior cycle's
    /// render retired" before the producer overwrites the slot. `None`
    /// for non-ring producers (single-shot exports) where no reuse
    /// race exists.
    acquire_release: Option<VkSlotRelease>,
}

#[cfg(any(unix, target_os = "wasi", target_os = "hermit"))]
impl VkOpaqueFd {
    /// Adopt a freshly-minted `OwnedFd` (typically the
    /// `VkMemoryGetFdInfoKHR` result) plus its [`VkOpaqueExportDesc`].
    ///
    /// Use [`Self::from_shared_fd`] instead whenever the producer
    /// already holds a long-lived `Arc<OwnedFd>` per pool slot — see its
    /// doc for why per-frame fd identity is load-bearing.
    #[inline]
    pub fn new(fd: OwnedFd, desc: VkOpaqueExportDesc) -> Result<Self, InvalidHandleError> {
        Self::from_shared_fd(Arc::new(fd), desc)
    }

    /// Construct from a pre-existing `Arc<OwnedFd>` — the producer's
    /// shared reference is preserved end-to-end without an
    /// intermediate `dup(2)`. This is the **stable-identity**
    /// constructor: every per-frame carrier built from the same
    /// producer slot has the same `Arc::as_ptr` identity AND the
    /// same underlying raw fd value, which keeps the
    /// `glImportMemoryFdEXT` / `vkAllocateMemory(VkImportMemoryFdInfoKHR)`
    /// import idempotent per-slot.
    ///
    /// Use this whenever the producer has a long-lived
    /// `Arc<OwnedFd>` per pool slot (e.g. an FFmpeg-Vulkan intermediate
    /// pool, or a camera-RAW SDK decoder's worker pool). Use
    /// [`Self::new`] only when you're handing the carrier a
    /// freshly-minted `OwnedFd` whose ownership the carrier should adopt.
    ///
    /// **Why this matters on NVIDIA Windows GL**:
    /// `glImportMemoryWin32HandleEXT` (and its `Fd` sibling) refuses
    /// the SECOND import of the same underlying kernel memory
    /// object — returns `GL_INVALID_OPERATION` ("already imported").
    /// Each `dup(2)` / `DuplicateHandle` creates a fresh raw value
    /// that points to the SAME underlying object; NVIDIA's driver
    /// tracks the underlying object, not the per-fd integer, and
    /// rejects the second import. Per-frame fd-dup therefore breaks
    /// a GL bridge's "mint once, cache forever" strategy. This
    /// constructor sidesteps that entirely.
    ///
    /// # Errors
    ///
    /// Rejects a zero `desc.size` and a degenerate `desc` extent. Every
    /// other field is inert metadata the importer reads back verbatim —
    /// see [`VkOpaqueExportDesc`].
    pub fn from_shared_fd(fd: Arc<OwnedFd>, desc: VkOpaqueExportDesc) -> Result<Self, InvalidHandleError> {
        if desc.size == 0 {
            return Err(InvalidHandleError::ZeroSize("VkOpaqueFd"));
        }
        if desc.width == 0 || desc.height == 0 {
            return Err(InvalidHandleError::InvalidValue { field: "extent" });
        }
        Ok(Self {
            fd,
            desc,
            plane_format: None,
            vk_image_usage: None,
            acquire_timeline: None,
            acquire_binary: None,
            acquire_release: None,
        })
    }

    /// Attach a per-plane storage format hint. Use when the exported
    /// memory backs a single plane of a multi-plane format (e.g. NV12
    /// luma alone) — the consumer-side importer maps this directly to
    /// the wgpu single-channel texture format instead of trying to
    /// re-derive it from [`Self::format`].
    #[inline]
    pub fn with_plane_format(mut self, plane_format: crate::PlaneFormat) -> Self {
        self.plane_format = Some(plane_format);
        self
    }

    /// Attach the producer-side `VkImageUsageFlags`. Required for
    /// Vulkan→Vulkan OPAQUE imports so the consumer's
    /// `VkImageCreateInfo` matches exactly — see field doc.
    #[inline]
    pub fn with_vk_image_usage(mut self, usage: u32) -> Self {
        self.vk_image_usage = Some(usage);
        self
    }

    /// Attach a GPU-side acquire-sync timeline — see
    /// [`VkAcquireTimeline`]. When stamped, the consumer is expected to
    /// chain a GPU wait on the producer's exported TIMELINE semaphore
    /// at the carried `value` before its first read; the producer
    /// elides its own CPU-side post-wait. Unstamped carriers
    /// guarantee CPU-visibility of the memory on hand-off.
    #[inline]
    pub fn with_acquire_timeline(mut self, timeline: VkAcquireTimeline) -> Self {
        self.acquire_timeline = Some(timeline);
        self
    }

    /// Attach a per-frame fresh BINARY acquire semaphore — see
    /// [`VkAcquireBinary`]. Used as a fallback when the consumer
    /// can't wire the timeline-import path (typical NVIDIA Windows
    /// GL combo where `GL_NV_timeline_semaphore + OPAQUE_WIN32`
    /// returns `GL_INVALID_VALUE` and D3D12_FENCE export is
    /// IMPORTABLE-only). Consumer dispatch order: timeline first,
    /// binary second; either successful wait acks its own capability
    /// channel and triggers producer-side post-wait elision.
    #[inline]
    pub fn with_acquire_binary(mut self, binary: VkAcquireBinary) -> Self {
        self.acquire_binary = Some(binary);
        self
    }

    /// Attach a consumer→producer slot-release back-pressure gate
    /// — see [`VkSlotRelease`] field docs.
    #[inline]
    pub fn with_acquire_release(mut self, release: VkSlotRelease) -> Self {
        self.acquire_release = Some(release);
        self
    }

    #[inline]
    pub fn fd(&self) -> &Arc<OwnedFd> {
        &self.fd
    }
    /// The whole validated export descriptor, as handed to
    /// [`Self::from_shared_fd`]. Re-emitting a carrier over a `dup`ed fd
    /// is `VkOpaqueFd::new(dup, *src.desc())` — no field-by-field
    /// re-assembly, so a new descriptor field cannot be silently
    /// dropped on the way through.
    #[inline]
    pub fn desc(&self) -> &VkOpaqueExportDesc {
        &self.desc
    }
    #[inline]
    pub fn size(&self) -> u64 {
        self.desc.size
    }
    /// `VkMemoryAllocateInfo::memoryTypeIndex` the producer allocated
    /// with — the importer MUST pass this exact index (see
    /// [`VkOpaqueExportDesc::memory_type_index`] for the two VUs).
    #[inline]
    pub fn memory_type_index(&self) -> u32 {
        self.desc.memory_type_index
    }
    #[inline]
    pub fn offset(&self) -> u64 {
        self.desc.offset
    }
    #[inline]
    pub fn dedicated(&self) -> bool {
        self.desc.dedicated
    }
    #[inline]
    pub fn width(&self) -> u32 {
        self.desc.width
    }
    #[inline]
    pub fn height(&self) -> u32 {
        self.desc.height
    }
    #[inline]
    pub fn format(&self) -> PixelFormat {
        self.desc.format
    }
    /// Per-plane storage hint set via [`Self::with_plane_format`].
    /// Consumers prefer this over [`Self::format`] when present.
    #[inline]
    pub fn plane_format(&self) -> Option<crate::PlaneFormat> {
        self.plane_format
    }
    /// Producer-side `VkImageUsageFlags` set via
    /// [`Self::with_vk_image_usage`]. Consumers mirror this on the
    /// import-side VkImage to keep VkImageCreateInfo identical.
    #[inline]
    pub fn vk_image_usage(&self) -> Option<u32> {
        self.vk_image_usage
    }
    /// Producer-side acquire-sync timeline. See
    /// [`Self::with_acquire_timeline`] / [`VkAcquireTimeline`].
    #[inline]
    pub fn acquire_timeline(&self) -> Option<&VkAcquireTimeline> {
        self.acquire_timeline.as_ref()
    }
    /// Producer-side per-frame fresh BINARY acquire semaphore. See
    /// [`Self::with_acquire_binary`] / [`VkAcquireBinary`].
    #[inline]
    pub fn acquire_binary(&self) -> Option<&VkAcquireBinary> {
        self.acquire_binary.as_ref()
    }
    /// Consumer→producer slot-release back-pressure gate. See
    /// [`Self::with_acquire_release`] / [`VkSlotRelease`].
    #[inline]
    pub fn acquire_release(&self) -> Option<&VkSlotRelease> {
        self.acquire_release.as_ref()
    }
    #[inline]
    pub fn uuid(&self) -> [u8; 16] {
        self.desc.uuid
    }
}

#[cfg(any(unix, target_os = "wasi", target_os = "hermit"))]
impl fmt::Debug for VkOpaqueFd {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        use std::os::fd::AsRawFd;
        f.debug_struct("VkOpaqueFd").field("fd", &self.fd.as_raw_fd()).field("desc", &self.desc).finish()
    }
}

/// Vulkan opaque-handle (NT) export via `VK_KHR_external_memory_win32`.
/// Symmetric Windows counterpart of `VkOpaqueFd`.
///
/// `VkOpaqueFd` is `#[cfg(unix)]` and this type is `#[cfg(windows)]`, so
/// the two never coexist in one build; references to it below are plain
/// code spans rather than intra-doc links because no rustdoc target can
/// ever resolve them.
#[cfg(windows)]
#[derive(Clone)]
pub struct VkOpaqueWin32 {
    handle: Arc<OwnedHandle>,
    /// Validated at construction, never re-exposed mutably — see
    /// [`VkOpaqueExportDesc`]. Read back field-by-field through
    /// [`Self::size`], [`Self::offset`], … or whole via [`Self::desc`].
    desc: VkOpaqueExportDesc,
    /// Per-plane storage format hint — see `VkOpaqueFd::plane_format`.
    plane_format: Option<crate::PlaneFormat>,
    /// Producer-side `VkImageUsageFlags`. See
    /// `VkOpaqueFd::vk_image_usage` for the full rationale — same
    /// invariant: the consumer-side `VkImageCreateInfo.usage` MUST
    /// match the producer's exactly, or NVIDIA's DCC metadata
    /// desynchronises across the device boundary (visible as
    /// horizontal stripes / progressive corruption / DEVICE_LOST).
    vk_image_usage: Option<u32>,
    /// Producer-side acquire-sync timeline — see
    /// `VkOpaqueFd::acquire_timeline` for the contract.
    acquire_timeline: Option<VkAcquireTimeline>,
    /// Producer-side per-frame fresh BINARY acquire semaphore — see
    /// `VkOpaqueFd::acquire_binary` for the contract.
    acquire_binary: Option<VkAcquireBinary>,
    /// Consumer→producer slot-release back-pressure carrier — see
    /// `VkOpaqueFd::acquire_release` for the contract.
    acquire_release: Option<VkSlotRelease>,
}

#[cfg(windows)]
impl VkOpaqueWin32 {
    /// Adopt a freshly-minted `OwnedHandle` (typically the
    /// `vkGetMemoryWin32HandleKHR` result) plus its
    /// [`VkOpaqueExportDesc`].
    ///
    /// Use [`Self::from_shared_handle`] instead whenever the producer
    /// already holds a long-lived `Arc<OwnedHandle>` per pool slot — see
    /// its doc for why per-frame handle identity is load-bearing.
    #[inline]
    pub fn new(handle: OwnedHandle, desc: VkOpaqueExportDesc) -> Result<Self, InvalidHandleError> {
        Self::from_shared_handle(Arc::new(handle), desc)
    }

    /// Construct from a pre-existing `Arc<OwnedHandle>` — the
    /// producer's shared reference is preserved end-to-end without
    /// an intermediate `DuplicateHandle`. See
    /// `VkOpaqueFd::from_shared_fd` for the full rationale; same
    /// argument applies on Windows for
    /// `glImportMemoryWin32HandleEXT` and `vkAllocateMemory(VkImportMemoryWin32HandleInfoKHR)`.
    ///
    /// # Errors
    ///
    /// Rejects a zero `desc.size` and a degenerate `desc` extent. Every
    /// other field is inert metadata the importer reads back verbatim —
    /// see [`VkOpaqueExportDesc`].
    pub fn from_shared_handle(handle: Arc<OwnedHandle>, desc: VkOpaqueExportDesc) -> Result<Self, InvalidHandleError> {
        if desc.size == 0 {
            return Err(InvalidHandleError::ZeroSize("VkOpaqueWin32"));
        }
        if desc.width == 0 || desc.height == 0 {
            return Err(InvalidHandleError::InvalidValue { field: "extent" });
        }
        Ok(Self {
            handle,
            desc,
            plane_format: None,
            vk_image_usage: None,
            acquire_timeline: None,
            acquire_binary: None,
            acquire_release: None,
        })
    }

    /// Attach a per-plane storage format hint. Use when the exported
    /// memory backs a single plane (e.g. NV12 luma) rather than the
    /// full multi-plane surface. See `VkOpaqueFd::with_plane_format`.
    #[inline]
    pub fn with_plane_format(mut self, plane_format: crate::PlaneFormat) -> Self {
        self.plane_format = Some(plane_format);
        self
    }

    /// Attach the producer-side `VkImageUsageFlags`. See
    /// `VkOpaqueFd::with_vk_image_usage`.
    #[inline]
    pub fn with_vk_image_usage(mut self, usage: u32) -> Self {
        self.vk_image_usage = Some(usage);
        self
    }

    /// Attach a GPU-side acquire-sync timeline — see
    /// `VkOpaqueFd::with_acquire_timeline`.
    #[inline]
    pub fn with_acquire_timeline(mut self, timeline: VkAcquireTimeline) -> Self {
        self.acquire_timeline = Some(timeline);
        self
    }

    /// Attach a per-frame fresh BINARY acquire semaphore — see
    /// `VkOpaqueFd::with_acquire_binary`.
    #[inline]
    pub fn with_acquire_binary(mut self, binary: VkAcquireBinary) -> Self {
        self.acquire_binary = Some(binary);
        self
    }

    /// Attach a consumer→producer slot-release back-pressure gate
    /// — see [`VkSlotRelease`] field docs.
    #[inline]
    pub fn with_acquire_release(mut self, release: VkSlotRelease) -> Self {
        self.acquire_release = Some(release);
        self
    }

    #[inline]
    pub fn handle(&self) -> &Arc<OwnedHandle> {
        &self.handle
    }
    /// The whole validated export descriptor, as handed to
    /// [`Self::from_shared_handle`]. Re-emitting a carrier over a
    /// `DuplicateHandle`d NT handle is
    /// `VkOpaqueWin32::new(dup, *src.desc())` — no field-by-field
    /// re-assembly, so a new descriptor field cannot be silently
    /// dropped on the way through.
    #[inline]
    pub fn desc(&self) -> &VkOpaqueExportDesc {
        &self.desc
    }
    #[inline]
    pub fn size(&self) -> u64 {
        self.desc.size
    }
    /// `VkMemoryAllocateInfo::memoryTypeIndex` the producer allocated
    /// with — the importer MUST pass this exact index (see
    /// [`VkOpaqueExportDesc::memory_type_index`] for the two VUs).
    #[inline]
    pub fn memory_type_index(&self) -> u32 {
        self.desc.memory_type_index
    }
    #[inline]
    pub fn offset(&self) -> u64 {
        self.desc.offset
    }
    #[inline]
    pub fn dedicated(&self) -> bool {
        self.desc.dedicated
    }
    #[inline]
    pub fn width(&self) -> u32 {
        self.desc.width
    }
    #[inline]
    pub fn height(&self) -> u32 {
        self.desc.height
    }
    #[inline]
    pub fn format(&self) -> PixelFormat {
        self.desc.format
    }
    /// Per-plane storage hint set via [`Self::with_plane_format`].
    /// Consumers prefer this over [`Self::format`] when present.
    #[inline]
    pub fn plane_format(&self) -> Option<crate::PlaneFormat> {
        self.plane_format
    }
    /// Producer-side `VkImageUsageFlags` set via
    /// [`Self::with_vk_image_usage`]. Consumers mirror this on the
    /// import-side VkImage to keep VkImageCreateInfo identical.
    #[inline]
    pub fn vk_image_usage(&self) -> Option<u32> {
        self.vk_image_usage
    }
    /// Producer-side acquire-sync timeline. See
    /// [`Self::with_acquire_timeline`] / [`VkAcquireTimeline`].
    #[inline]
    pub fn acquire_timeline(&self) -> Option<&VkAcquireTimeline> {
        self.acquire_timeline.as_ref()
    }
    /// Producer-side per-frame fresh BINARY acquire semaphore. See
    /// [`Self::with_acquire_binary`] / [`VkAcquireBinary`].
    #[inline]
    pub fn acquire_binary(&self) -> Option<&VkAcquireBinary> {
        self.acquire_binary.as_ref()
    }
    /// Consumer→producer slot-release back-pressure gate. See
    /// [`Self::with_acquire_release`] / [`VkSlotRelease`].
    #[inline]
    pub fn acquire_release(&self) -> Option<&VkSlotRelease> {
        self.acquire_release.as_ref()
    }
    #[inline]
    pub fn uuid(&self) -> [u8; 16] {
        self.desc.uuid
    }
}

#[cfg(windows)]
impl fmt::Debug for VkOpaqueWin32 {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // The NT handle itself is deliberately omitted (a raw kernel
        // handle value is noise in a log); the descriptor is the part
        // that diagnoses an import mismatch.
        f.debug_struct("VkOpaqueWin32").field("desc", &self.desc).finish()
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// D3D11 / D3D12
// ─────────────────────────────────────────────────────────────────────────────

/// `ID3D11Texture2D*` keyed-mutex / shared-handle resource.
#[derive(Clone)]
pub struct D3D11Texture {
    texture: *mut c_void,
    luid: Option<(i32, u32)>,
    row_pitch: u32,
    /// Producer-side array-slice index when `texture` is a pool-array
    /// `ID3D11Texture2D` (`ArraySize > 1`). Defaults to `0` and is
    /// ignored by importers when the resource is non-array. FFmpeg's
    /// D3D11VA hwaccel sets this to `AVFrame.data[1]` so the consumer
    /// can target the specific decoded slice; without it every import
    /// reads slice 0 of the pool, which never contains the current
    /// frame's data.
    array_slice: u32,
    keep_alive: Option<KeepAlive>,
}

impl D3D11Texture {
    /// Wrap a raw `ID3D11Texture2D*`. *Borrowing*: the handle is stored
    /// non-owningly, this type has no [`Drop`], and every obligation below
    /// extends to each [`Clone`].
    ///
    /// # Safety
    ///
    /// * `texture` must point to a live `ID3D11Texture2D` (or an
    ///   `ID3D11Resource` whose `QueryInterface` for `ID3D11Texture2D`
    ///   succeeds). It is stored verbatim, and the importer calls COM
    ///   methods through the vtable at that address, so any other object
    ///   type is undefined behaviour. Null is rejected as
    ///   [`InvalidHandleError::NullPointer`] and is not a caller
    ///   obligation.
    /// * **Refcount:** this does *not* `AddRef`, and there is no `Drop`
    ///   that would `Release`. The caller keeps its own reference and
    ///   must not `Release` it while this value or any [`Clone`] of it
    ///   is reachable — every clone copies the bare interface pointer,
    ///   so a premature `Release` leaves live clones pointing at freed
    ///   memory. Pass a `keep_alive` anchor holding the producer's
    ///   reference to discharge this; with `None` the caller carries it.
    /// * **Cross-thread:** `D3D11Texture` is `Send + Sync`, and that is
    ///   sound only because the caller asserts the producer enabled
    ///   D3D11's multithread protection for this resource — either
    ///   `D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX` /
    ///   `D3D11_RESOURCE_MISC_SHARED_NTHANDLE` on the texture, or
    ///   `ID3D11Multithread::SetMultithreadProtected(TRUE)` on the
    ///   owning device. D3D11 device contexts are otherwise *not*
    ///   free-threaded; without one of these the interop threads race
    ///   the producer's immediate context.
    /// * `luid`, when `Some`, must be the `LUID` of the adapter the
    ///   texture lives on; importers use it to refuse cross-adapter
    ///   opens.
    /// * `row_pitch` must be the producer's mapped row pitch in bytes,
    ///   or `0` when unknown — consumers size staging copies from it.
    pub unsafe fn try_from_raw(
        texture: *mut c_void,
        luid: Option<(i32, u32)>,
        row_pitch: u32,
        keep_alive: Option<KeepAlive>,
    ) -> Result<Self, InvalidHandleError> {
        if texture.is_null() {
            return Err(InvalidHandleError::NullPointer("ID3D11Texture2D"));
        }
        Ok(Self { texture, luid, row_pitch, array_slice: 0, keep_alive })
    }

    /// Pin the producer-side array slice index on a pool-array
    /// `ID3D11Texture2D`. Mirrors the producer's `AVFrame.data[1]` (or
    /// equivalent) so the importer can copy or view the right slice.
    /// No-op on non-array sources (importers check the resource's own
    /// `ArraySize` first).
    #[inline]
    pub fn with_array_slice(mut self, slice: u32) -> Self {
        self.array_slice = slice;
        self
    }

    #[inline]
    pub fn texture(&self) -> *mut c_void {
        self.texture
    }
    #[inline]
    pub fn luid(&self) -> Option<(i32, u32)> {
        self.luid
    }
    #[inline]
    pub fn row_pitch(&self) -> u32 {
        self.row_pitch
    }
    #[inline]
    pub fn array_slice(&self) -> u32 {
        self.array_slice
    }
    #[inline]
    pub fn keep_alive(&self) -> Option<&KeepAlive> {
        self.keep_alive.as_ref()
    }
}

impl fmt::Debug for D3D11Texture {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("D3D11Texture")
            .field("luid", &self.luid)
            .field("row_pitch", &self.row_pitch)
            .field("array_slice", &self.array_slice)
            .finish()
    }
}

// SAFETY: caller-asserted multithread-protect contract (see
// `try_from_raw` docs).
unsafe impl Send for D3D11Texture {}
unsafe impl Sync for D3D11Texture {}

/// `ID3D12Resource*` keyed-mutex / shared-handle resource (Texture2D
/// dimension).
#[derive(Clone)]
pub struct D3D12Resource {
    resource: *mut c_void,
    luid: Option<(i32, u32)>,
    row_pitch: u32,
    keep_alive: Option<KeepAlive>,
}

impl D3D12Resource {
    /// Wrap a raw Texture2D-dimension `ID3D12Resource*`. *Borrowing*: the
    /// handle is stored non-owningly, this type has no [`Drop`], and every
    /// obligation below extends to each [`Clone`].
    ///
    /// # Safety
    ///
    /// * `resource` must point to a live `ID3D12Resource` of
    ///   `D3D12_RESOURCE_DIMENSION_TEXTURE2D`. It is stored verbatim and
    ///   the importer calls COM methods through the vtable at that
    ///   address. Null is rejected as
    ///   [`InvalidHandleError::NullPointer`] and is not a caller
    ///   obligation.
    /// * **Refcount:** no `AddRef` is taken and there is no `Drop` that
    ///   would `Release`. The caller's reference must outlive this value
    ///   and every [`Clone`] of it; pass a `keep_alive` anchor to
    ///   discharge that, or carry it directly when `None`.
    /// * **Cross-thread:** unlike D3D11 this needs no opt-in — D3D12
    ///   objects are free-threaded by specification, which is what makes
    ///   the `unsafe impl Send + Sync` below sound. The caller is still
    ///   responsible for the usual D3D12 rules the importer cannot see:
    ///   the resource must be in a state compatible with what the
    ///   importer will transition from, and must not be evicted.
    /// * `luid`, when `Some`, must be the `LUID` of the adapter the
    ///   resource lives on; importers use it to refuse cross-adapter
    ///   opens.
    /// * `row_pitch` must be the resource's footprint row pitch in
    ///   bytes, or `0` when unknown.
    pub unsafe fn try_from_raw(
        resource: *mut c_void,
        luid: Option<(i32, u32)>,
        row_pitch: u32,
        keep_alive: Option<KeepAlive>,
    ) -> Result<Self, InvalidHandleError> {
        if resource.is_null() {
            return Err(InvalidHandleError::NullPointer("ID3D12Resource"));
        }
        Ok(Self { resource, luid, row_pitch, keep_alive })
    }

    #[inline]
    pub fn resource(&self) -> *mut c_void {
        self.resource
    }
    #[inline]
    pub fn luid(&self) -> Option<(i32, u32)> {
        self.luid
    }
    #[inline]
    pub fn row_pitch(&self) -> u32 {
        self.row_pitch
    }
    #[inline]
    pub fn keep_alive(&self) -> Option<&KeepAlive> {
        self.keep_alive.as_ref()
    }
}

impl fmt::Debug for D3D12Resource {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("D3D12Resource").field("luid", &self.luid).field("row_pitch", &self.row_pitch).finish()
    }
}

unsafe impl Send for D3D12Resource {}
unsafe impl Sync for D3D12Resource {}

/// Buffer-dimension `ID3D12Resource*` (committed with
/// `Dimension = D3D12_RESOURCE_DIMENSION_BUFFER`).
#[derive(Clone)]
pub struct D3D12BufferHandle {
    resource: *mut c_void,
    luid: Option<(i32, u32)>,
    size: u64,
    keep_alive: Option<KeepAlive>,
}

impl D3D12BufferHandle {
    /// Wrap a raw buffer-dimension `ID3D12Resource*`. *Borrowing*: the
    /// handle is stored non-owningly, this type has no [`Drop`], and every
    /// obligation below extends to each [`Clone`].
    ///
    /// # Safety
    ///
    /// * `resource` must point to a live `ID3D12Resource` committed with
    ///   `D3D12_RESOURCE_DIMENSION_BUFFER`. Handing a texture-dimension
    ///   resource here type-confuses every consumer, which addresses it
    ///   linearly.
    /// * `size` must not exceed the resource's actual `Width` in bytes —
    ///   consumers copy `size` bytes out of it. Zero is rejected as
    ///   [`InvalidHandleError::ZeroSize`], null as
    ///   [`InvalidHandleError::NullPointer`]; neither is a caller
    ///   obligation.
    /// * Refcount, lifetime, cross-thread and `luid` obligations are
    ///   exactly those of [`D3D12Resource::try_from_raw`]: no `AddRef`,
    ///   no `Drop`, the caller's reference must outlive every [`Clone`].
    pub unsafe fn try_from_raw(
        resource: *mut c_void,
        luid: Option<(i32, u32)>,
        size: u64,
        keep_alive: Option<KeepAlive>,
    ) -> Result<Self, InvalidHandleError> {
        if resource.is_null() {
            return Err(InvalidHandleError::NullPointer("ID3D12Resource"));
        }
        if size == 0 {
            return Err(InvalidHandleError::ZeroSize("D3D12 buffer"));
        }
        Ok(Self { resource, luid, size, keep_alive })
    }

    #[inline]
    pub fn resource(&self) -> *mut c_void {
        self.resource
    }
    #[inline]
    pub fn luid(&self) -> Option<(i32, u32)> {
        self.luid
    }
    #[inline]
    pub fn size(&self) -> u64 {
        self.size
    }
    #[inline]
    pub fn keep_alive(&self) -> Option<&KeepAlive> {
        self.keep_alive.as_ref()
    }
}

impl fmt::Debug for D3D12BufferHandle {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("D3D12BufferHandle").field("luid", &self.luid).field("size", &self.size).finish()
    }
}

unsafe impl Send for D3D12BufferHandle {}
unsafe impl Sync for D3D12BufferHandle {}

// ─────────────────────────────────────────────────────────────────────────────
// Windows shared-handle tokens
// ─────────────────────────────────────────────────────────────────────────────

/// Generic Windows NT shared-handle wrapper. Used for keyed-mutex /
/// fence-share / D3D12 NT handles whose lifetime must outlive any caller
/// reference, with `CloseHandle` running on last drop (via std's
/// `OwnedHandle::drop`).
#[cfg(windows)]
#[derive(Clone)]
pub struct NtHandle {
    handle: Arc<OwnedHandle>,
}

#[cfg(windows)]
impl NtHandle {
    pub fn new(handle: OwnedHandle) -> Self {
        Self { handle: Arc::new(handle) }
    }

    #[inline]
    pub fn handle(&self) -> &Arc<OwnedHandle> {
        &self.handle
    }
}

#[cfg(windows)]
impl fmt::Debug for NtHandle {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("NtHandle").finish_non_exhaustive()
    }
}

/// DXGI KMT (kernel-mode thunk) shared handle token. Just a `u32` table
/// id — not an NT-handle, no `CloseHandle` semantics. KMT tokens are
/// DXGI-only; the variant is `#[cfg(windows)]` because cross-platform
/// consumers have nothing to do with KMT.
#[cfg(windows)]
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct KmtToken(u32);

#[cfg(windows)]
impl KmtToken {
    pub fn new(value: u32) -> Result<Self, InvalidHandleError> {
        if value == 0 {
            return Err(InvalidHandleError::InvalidValue { field: "KMT token" });
        }
        Ok(Self(value))
    }

    #[inline]
    pub fn value(self) -> u32 {
        self.0
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// CUDA
// ─────────────────────────────────────────────────────────────────────────────

/// 2D (pitched) CUDA device pointer (`CUdeviceptr` aliased as `u64`).
///
/// For multi-plane formats (NV12 / P010 / I420 …) `ptr` points at the
/// first plane (Y). Subsequent planes live at producer-defined byte
/// offsets carried in [`Self::plane_byte_offsets`] — when set, the
/// importer trusts them verbatim. When `None`, importers fall back to
/// the trivial format-inferred offset (`row_pitch * height` for plane
/// 1 in NV12 / P010, etc.), which only matches producers that allocate
/// planes back-to-back at the user-specified height. NVDEC's
/// `cuMemAllocPitch` pool rounds the Y-plane footprint up to a
/// driver-chosen alignment, so producers wrapping NVDEC frames must call
/// [`Self::with_plane_byte_offsets`] with the actual `data[i] -
/// data[0]` offsets they observed.
///
/// **Intrinsic dimensions.** Unlike `D3D11Texture` / `VkImage` /
/// `MetalTextureHandle`, a `CUdeviceptr` is opaque memory — there is
/// no driver-side metadata to query for `(width, height)`. Producers
/// that know the logical dimensions attach them via
/// [`Self::with_size`], and any importer that wasn't given an explicit
/// size from the caller side falls back to this hint — an auto-import
/// path typically has no size context of its own.
#[derive(Clone)]
pub struct CudaPtr2D {
    ptr: u64,
    row_pitch: u32,
    /// Byte offsets of planes 1..=3 relative to `ptr`. `None` =
    /// "infer from format" (single-plane / contiguous-pool callers).
    /// The array indices map to planes 1, 2, 3 — plane 0
    /// always lives at offset 0 (`ptr` itself).
    plane_byte_offsets: Option<[u32; 3]>,
    /// Device row pitch (bytes) of planes 1..=3, indexed the same way as
    /// [`Self::plane_byte_offsets`] (plane 0's pitch is [`Self::row_pitch`]).
    /// `None` = "all planes share [`Self::row_pitch`]" — the NVDEC /
    /// `cuMemAllocPitch` single-allocation contract, where every plane
    /// is tied to one pitch. Producers whose planes carry *independent*
    /// row pitches (a triplanar source whose subsampled U/V planes were
    /// allocated with their own, narrower pitch) attach them via
    /// [`Self::with_plane_row_pitches`] so per-plane consumers (a CUDA
    /// YUV→RGB kernel, say) index each plane's rows by its true
    /// device pitch instead of assuming proportionality to luma.
    plane_row_pitches: Option<[u32; 3]>,
    /// Logical dimensions of the foreign frame (luma plane for
    /// multi-plane formats). `None` when the producer didn't attach
    /// them; importers then require the caller to pass an explicit
    /// size with the import instead.
    size: Option<(u32, u32)>,
    /// Pixel format of the foreign frame. `None` when the producer
    /// didn't attach it; importers then require an explicit format.
    format: Option<PixelFormat>,
    uuid: Option<[u8; 16]>,
    keep_alive: Option<KeepAlive>,
}

impl CudaPtr2D {
    /// Wrap a raw pitched `CUdeviceptr`. *Borrowing*: the handle is stored
    /// non-owningly, this type has no [`Drop`], and every obligation below
    /// extends to each [`Clone`].
    ///
    /// # Safety
    ///
    /// * `ptr` must be a live `CUdeviceptr` — device memory that is
    ///   currently allocated (`cuMemAlloc`, `cuMemAllocPitch`, an NVDEC
    ///   pool slot, or a `cuExternalMemoryGetMappedBuffer` mapping) and
    ///   not yet freed. Only `ptr == 0` is checked, and it is reported
    ///   as [`InvalidHandleError::NullHandle`] rather than being a
    ///   caller obligation.
    /// * **Context affinity.** A `CUdeviceptr` is meaningful only inside
    ///   the CUDA context that allocated it (or a context sharing its
    ///   address space via unified addressing). The caller must ensure
    ///   the consumer runs against that context; the handle carries no
    ///   context of its own, only `uuid`.
    /// * `uuid`, when `Some`, must equal the CUDA device's
    ///   `CUuuid` as reported by `cuDeviceGetUuid`. Importers compare it
    ///   against the wgpu adapter's UUID to refuse cross-GPU imports; a
    ///   wrong value defeats that check.
    /// * `row_pitch` must be the plane-0 device row pitch in bytes, as
    ///   returned by `cuMemAllocPitch` or reported by the producer. It
    ///   is what every consumer multiplies by the row index, so an
    ///   under-sized value reads a shifted image and an over-sized one
    ///   reads past the allocation.
    /// * **Extent:** this constructor is given no dimensions, so nothing
    ///   here bounds the reads a consumer will make. The allocation must
    ///   be large enough for whatever extent the consumer is later told
    ///   about — via [`Self::with_size`] or the caller's import size — at
    ///   `row_pitch` stride, including every plane reachable through
    ///   [`Self::with_plane_byte_offsets`] /
    ///   [`Self::with_plane_row_pitches`].
    /// * Lifetime: nothing is retained and there is no `Drop`, so
    ///   `cuMemFree` (or the pool slot's recycle) must not run while
    ///   this value or any [`Clone`] of it is reachable. Pass a
    ///   `keep_alive` anchor to discharge that; with `None` the caller
    ///   carries it.
    /// * No thread affinity beyond CUDA's own: the pointer is valid on
    ///   any thread that has the owning context current, which is what
    ///   backs the `unsafe impl Send + Sync` below.
    pub unsafe fn try_from_raw(
        ptr: u64,
        row_pitch: u32,
        uuid: Option<[u8; 16]>,
        keep_alive: Option<KeepAlive>,
    ) -> Result<Self, InvalidHandleError> {
        if ptr == 0 {
            return Err(InvalidHandleError::NullHandle("CUdeviceptr"));
        }
        Ok(Self {
            ptr,
            row_pitch,
            plane_byte_offsets: None,
            plane_row_pitches: None,
            size: None,
            format: None,
            uuid,
            keep_alive,
        })
    }

    /// Attach explicit per-plane byte offsets (planes 1, 2, 3 relative
    /// to `ptr`). Used by producers whose pool layout deviates from
    /// the trivial `row_pitch * height` rule — NVDEC being the
    /// canonical example. Pass `0` for unused tail entries.
    #[inline]
    pub fn with_plane_byte_offsets(mut self, offsets: [u32; 3]) -> Self {
        self.plane_byte_offsets = Some(offsets);
        self
    }

    /// Attach explicit per-plane device row pitches (bytes) for planes
    /// 1, 2, 3 (plane 0 uses [`Self::row_pitch`]). Required only when a
    /// producer's planes do NOT all share one pitch; the NVDEC /
    /// `cuMemAllocPitch` single-allocation layout ties every plane to
    /// `row_pitch`, so those producers leave this `None`. Pass `0` for
    /// unused tail entries.
    #[inline]
    pub fn with_plane_row_pitches(mut self, pitches: [u32; 3]) -> Self {
        self.plane_row_pitches = Some(pitches);
        self
    }

    /// Attach the logical `(width, height)` of the foreign frame
    /// (luma plane for multi-plane formats). See the struct-level
    /// docs for why CUDA needs this when D3D11 / Vulkan / Metal don't.
    #[inline]
    pub fn with_size(mut self, width: u32, height: u32) -> Self {
        self.size = Some((width, height));
        self
    }

    /// Attach the pixel format of the foreign frame. Importers fall
    /// back to this when the caller passes no explicit format.
    #[inline]
    pub fn with_format(mut self, format: PixelFormat) -> Self {
        self.format = Some(format);
        self
    }

    #[inline]
    pub fn ptr(&self) -> u64 {
        self.ptr
    }
    #[inline]
    pub fn row_pitch(&self) -> u32 {
        self.row_pitch
    }
    /// Per-plane byte offsets, when the producer attached them. See
    /// the struct-level docs for the semantics of `None`.
    #[inline]
    pub fn plane_byte_offsets(&self) -> Option<[u32; 3]> {
        self.plane_byte_offsets
    }
    /// Raw per-plane device row pitches (planes 1, 2, 3), when the
    /// producer attached them. `None` ⇒ every plane shares
    /// [`Self::row_pitch`]. Prefer [`Self::plane_row_pitch`] for the
    /// resolved-with-fallback value at a given plane index.
    #[inline]
    pub fn plane_row_pitches(&self) -> Option<[u32; 3]> {
        self.plane_row_pitches
    }
    /// Device row pitch (bytes) of plane `index`, resolved against the
    /// `None`-means-uniform contract: plane 0 (and any plane the
    /// producer left unset) returns [`Self::row_pitch`]; planes 1..=3
    /// return their explicit pitch when [`Self::with_plane_row_pitches`]
    /// supplied a non-zero entry. `index >= 4` clamps to plane 0.
    #[inline]
    pub fn plane_row_pitch(&self, index: u8) -> u32 {
        match index {
            1..=3 => self
                .plane_row_pitches
                .and_then(|p| p.get((index - 1) as usize).copied())
                .filter(|&pitch| pitch != 0)
                .unwrap_or(self.row_pitch),
            _ => self.row_pitch,
        }
    }
    /// Logical `(width, height)` hint, when the producer attached
    /// them. Importers fall back to this when no explicit
    /// import size is available.
    #[inline]
    pub fn size(&self) -> Option<(u32, u32)> {
        self.size
    }
    /// Pixel format hint. Importers fall back to this when the caller
    /// passes no explicit format.
    #[inline]
    pub fn format(&self) -> Option<PixelFormat> {
        self.format
    }
    #[inline]
    pub fn uuid(&self) -> Option<[u8; 16]> {
        self.uuid
    }
    #[inline]
    pub fn keep_alive(&self) -> Option<&KeepAlive> {
        self.keep_alive.as_ref()
    }
}

impl fmt::Debug for CudaPtr2D {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("CudaPtr2D")
            .field("row_pitch", &self.row_pitch)
            .field("plane_byte_offsets", &self.plane_byte_offsets)
            .field("plane_row_pitches", &self.plane_row_pitches)
            .field("size", &self.size)
            .field("format", &self.format)
            .field("uuid", &self.uuid)
            .finish()
    }
}

// SAFETY: CUDA device pointers are global to the CUDA context, safe to
// share across threads.
unsafe impl Send for CudaPtr2D {}
unsafe impl Sync for CudaPtr2D {}

/// 1D (flat) CUDA device pointer with byte size.
#[derive(Clone)]
pub struct CudaBufferHandle {
    ptr: u64,
    size: u64,
    uuid: Option<[u8; 16]>,
    keep_alive: Option<KeepAlive>,
}

impl CudaBufferHandle {
    /// Wrap a flat `CUdeviceptr` with an explicit byte size. *Borrowing*:
    /// the handle is stored non-owningly, this type has no [`Drop`], and
    /// every obligation below extends to each [`Clone`].
    ///
    /// # Safety
    ///
    /// * `ptr` must be a live `CUdeviceptr` addressing at least `size`
    ///   contiguous bytes of currently-allocated device memory.
    ///   Consumers read and write the whole `[ptr, ptr + size)` range,
    ///   so an over-stated `size` is an out-of-bounds device access.
    /// * `ptr == 0` is rejected as [`InvalidHandleError::NullHandle`]
    ///   and `size == 0` as [`InvalidHandleError::ZeroSize`]; neither is
    ///   a caller obligation.
    /// * Context affinity, `uuid`, lifetime (no retain, no `Drop`, must
    ///   outlive every [`Clone`], discharged by `keep_alive`) and
    ///   thread rules are exactly those of [`CudaPtr2D::try_from_raw`].
    pub unsafe fn try_from_raw(
        ptr: u64,
        size: u64,
        uuid: Option<[u8; 16]>,
        keep_alive: Option<KeepAlive>,
    ) -> Result<Self, InvalidHandleError> {
        if ptr == 0 {
            return Err(InvalidHandleError::NullHandle("CUdeviceptr"));
        }
        if size == 0 {
            return Err(InvalidHandleError::ZeroSize("CUDA buffer"));
        }
        Ok(Self { ptr, size, uuid, keep_alive })
    }

    #[inline]
    pub fn ptr(&self) -> u64 {
        self.ptr
    }
    #[inline]
    pub fn size(&self) -> u64 {
        self.size
    }
    #[inline]
    pub fn uuid(&self) -> Option<[u8; 16]> {
        self.uuid
    }
    #[inline]
    pub fn keep_alive(&self) -> Option<&KeepAlive> {
        self.keep_alive.as_ref()
    }
}

impl fmt::Debug for CudaBufferHandle {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("CudaBufferHandle").field("size", &self.size).field("uuid", &self.uuid).finish()
    }
}

unsafe impl Send for CudaBufferHandle {}
unsafe impl Sync for CudaBufferHandle {}

/// Opaque CUDA `CUsurfObject` bound to a `CUarray`, used as a
/// `surf2Dwrite` kernel write target.
///
/// Unlike [`CudaPtr2D`] (flat device memory) this wraps a *surface
/// object* — the driver handle a kernel writes through into a tiled
/// CUDA array. The array itself is typically a foreign-API texture
/// (D3D12 / Vulkan / GL) imported as a `CUmipmappedArray` → `CUarray`,
/// so a CUDA consumer writes post-YUV→RGB pixels straight into a
/// wgpu-readable driver-tiled texture with no intermediate copy.
///
/// `format` carries the array's element format (the wgpu render-target
/// format the producer allocated — `Rgba8Unorm` or `Rgba16Float`). It
/// is informational for the binding ABI (the kernel learns its output
/// format from the params blob, not this handle); it lets the bridge
/// and any diagnostics reason about the surface without a driver query.
/// Because the field is a `wgpu::TextureFormat`, the whole newtype is
/// gated on the crate's `wgpu` feature — matching the precedent set by
/// [`crate::PlaneFormat::to_wgpu_texture_format`]: backend-agnostic code
/// carries crate-native types, `wgpu` types appear only behind the gate.
///
/// `keep_alive` retains the underlying import chain
/// (`cuSurfObjectCreate` → `CUarray` → `CUmipmappedArray` →
/// `cuImportExternalMemory`) for at least the lifetime of any kernel
/// launch that receives this handle.
#[cfg(feature = "wgpu")]
#[derive(Clone)]
pub struct CudaSurface {
    surf: u64,
    width: u32,
    height: u32,
    format: wgpu::TextureFormat,
    uuid: Option<[u8; 16]>,
    keep_alive: Option<KeepAlive>,
}

#[cfg(feature = "wgpu")]
impl CudaSurface {
    /// Wrap a raw `CUsurfObject`. *Borrowing*: the handle is stored
    /// non-owningly, this type has no [`Drop`], and every obligation below
    /// extends to each [`Clone`].
    ///
    /// # Safety
    ///
    /// * `surf` must be a live `CUsurfObject` created by
    ///   `cuSurfObjectCreate` and not yet destroyed, on the CUDA device
    ///   identified by `uuid` when that is `Some`.
    /// * The bound `CUarray` must actually have element format `format`
    ///   and dimensions `width` × `height`. Kernels reached through this
    ///   handle issue `surf2Dwrite`s sized by `format` and clipped by
    ///   `width` / `height`; a mismatch writes the wrong number of bytes
    ///   per texel or past the array's last row. Zero extents are
    ///   rejected as [`InvalidHandleError::InvalidValue`] and a zero
    ///   `surf` as [`InvalidHandleError::NullHandle`], so neither is a
    ///   caller obligation.
    /// * **Lifetime — the whole import chain, not just the surface.**
    ///   `keep_alive` (or the caller, when it is `None`) must retain
    ///   every link of `cuSurfObjectCreate` → `CUarray` →
    ///   `CUmipmappedArray` → `cuImportExternalMemory`, and the foreign
    ///   texture underneath it, for at least as long as any kernel
    ///   launch that receives this handle can still be running. A
    ///   surface object outliving its array, or an array outliving the
    ///   external-memory import, is a use-after-free inside the kernel.
    ///   Nothing is retained here and there is no `Drop`.
    /// * The caller must not `cuSurfObjectDestroy` while this value or
    ///   any [`Clone`] of it is reachable.
    pub unsafe fn try_from_raw(
        surf: u64,
        width: u32,
        height: u32,
        format: wgpu::TextureFormat,
        uuid: Option<[u8; 16]>,
        keep_alive: Option<KeepAlive>,
    ) -> Result<Self, InvalidHandleError> {
        if surf == 0 {
            return Err(InvalidHandleError::NullHandle("CUsurfObject"));
        }
        if width == 0 || height == 0 {
            return Err(InvalidHandleError::InvalidValue { field: "extent" });
        }
        Ok(Self { surf, width, height, format, uuid, keep_alive })
    }

    #[inline]
    pub fn surf(&self) -> u64 {
        self.surf
    }
    #[inline]
    pub fn width(&self) -> u32 {
        self.width
    }
    #[inline]
    pub fn height(&self) -> u32 {
        self.height
    }
    #[inline]
    pub fn format(&self) -> wgpu::TextureFormat {
        self.format
    }
    #[inline]
    pub fn uuid(&self) -> Option<[u8; 16]> {
        self.uuid
    }
    #[inline]
    pub fn keep_alive(&self) -> Option<&KeepAlive> {
        self.keep_alive.as_ref()
    }
}

#[cfg(feature = "wgpu")]
impl fmt::Debug for CudaSurface {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("CudaSurface")
            .field("width", &self.width)
            .field("height", &self.height)
            .field("format", &self.format)
            .field("uuid", &self.uuid)
            .finish()
    }
}

// SAFETY: a CUsurfObject is a global driver handle, valid across threads
// under the same CUDA context — same contract as the other CUDA handles.
#[cfg(feature = "wgpu")]
unsafe impl Send for CudaSurface {}
#[cfg(feature = "wgpu")]
unsafe impl Sync for CudaSurface {}

// ─────────────────────────────────────────────────────────────────────────────
// Native wgpu texture (same-device passthrough)
// ─────────────────────────────────────────────────────────────────────────────

/// A native [`wgpu::Texture`] that already lives on the *consumer's own*
/// wgpu device — the zero-interop passthrough.
///
/// Every other [`crate::GpuResource`] variant wraps a *foreign* handle
/// (a D3D11 texture, a Vulkan opaque-fd, a CUDA pointer, …) that the
/// consumer must *import* onto its wgpu device before it can render. A
/// `WgpuTexture` is the degenerate case: the producer minted the texture
/// against the same device the consumer renders on, so there is nothing
/// to import — the consumer uses the handle directly. The interop import
/// path recognises this variant and returns the texture verbatim
/// (no driver round-trip, no copy).
///
/// Gated on the crate's `wgpu` feature for the same reason as
/// [`CudaSurface`]: it stores a `wgpu`-native type, and backend-agnostic
/// code must not pull `wgpu` in unconditionally.
///
/// # Lifetime
///
/// [`wgpu::Texture`] is itself an internally-refcounted handle — cloning
/// it bumps wgpu's own refcount and the last clone runs the destructor.
/// The stored `wgpu::Texture` therefore keeps the GPU **allocation**
/// alive on its own. The optional `keep_alive` pins the producer's
/// *content* lifetime instead — the same contract as every foreign
/// handle's keep-alive slot: a producer whose texture is a recyclable
/// pool/ring slot parks the slot lease here so the pool cannot re-issue
/// (and overwrite) the texture while any consumer-side clone of the
/// resource is still sampling it. An interop import passthrough threads
/// it onto the import result it returns, so the standard
/// hold-until-superseded import-lease discipline covers native wgpu
/// producers too. Cloning a `WgpuTexture` (and the `GpuResource` around
/// it) is one wgpu refcount bump plus one `Arc` bump when a keep-alive
/// is attached.
#[cfg(feature = "wgpu")]
#[derive(Clone)]
pub struct WgpuTexture {
    texture: wgpu::Texture,
    keep_alive: Option<KeepAlive>,
}

#[cfg(feature = "wgpu")]
impl WgpuTexture {
    /// Wrap a caller-owned `wgpu::Texture` that lives on the consumer's
    /// wgpu device. Safe — no raw handle invariant to assert; the
    /// `wgpu::Texture` is a checked, refcounted handle. No producer
    /// keep-alive is attached: use [`Self::with_keep_alive`] when the
    /// texture is a recyclable pool slot (see the `# Lifetime` note).
    #[inline]
    pub fn new(texture: wgpu::Texture) -> Self {
        Self { texture, keep_alive: None }
    }

    /// Attach the producer's keep-alive anchor (e.g. the RAII lease of
    /// the pool/ring slot backing this texture). Held by every clone of
    /// the resource and by an interop passthrough's import result; the
    /// producer's pool may recycle the slot only once the last holder
    /// drops.
    #[inline]
    pub fn with_keep_alive(mut self, keep_alive: KeepAlive) -> Self {
        self.keep_alive = Some(keep_alive);
        self
    }

    /// Borrow the wrapped texture.
    #[inline]
    pub fn texture(&self) -> &wgpu::Texture {
        &self.texture
    }

    /// The producer's keep-alive anchor, when one was attached.
    #[inline]
    pub fn keep_alive(&self) -> Option<&KeepAlive> {
        self.keep_alive.as_ref()
    }

    /// Consume the wrapper, returning the wrapped texture. Drops any
    /// attached producer keep-alive — for a pooled producer texture the
    /// caller must be done sampling the content (or hold the anchor via
    /// another clone) before calling this.
    #[inline]
    pub fn into_texture(self) -> wgpu::Texture {
        self.texture
    }
}

#[cfg(feature = "wgpu")]
impl fmt::Debug for WgpuTexture {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("WgpuTexture")
            .field("width", &self.texture.width())
            .field("height", &self.texture.height())
            .field("format", &self.texture.format())
            .field("keep_alive", &self.keep_alive.is_some())
            .finish()
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// OpenCL
// ─────────────────────────────────────────────────────────────────────────────

/// `cl_mem` handle paired with its producing `cl_command_queue`.
///
/// `row_pitch` is meaningful only for `cl_mem` BUFFER objects holding
/// image data with non-tight rows; see the documentation on the
/// `OpenCl` variant for the full contract.
#[derive(Clone)]
pub struct OpenClMem {
    mem: *mut c_void,
    queue: *mut c_void,
    row_pitch: u32,
    keep_alive: Option<KeepAlive>,
}

impl OpenClMem {
    /// Wrap a raw `cl_mem` together with the `cl_command_queue` that
    /// produced it. *Borrowing*: the handle is stored non-owningly, this
    /// type has no [`Drop`], and every obligation below extends to each
    /// [`Clone`].
    ///
    /// # Safety
    ///
    /// * `mem` must be a live `cl_mem` whose OpenCL reference count is
    ///   at least one.
    /// * `queue` must be a live `cl_command_queue` **on a context that
    ///   owns `mem`**. Consumers enqueue against `queue` naming `mem`;
    ///   an unrelated context makes that an invalid-object call at best
    ///   and undefined at worst. Null for either is rejected as
    ///   [`InvalidHandleError::NullPointer`] and is not a caller
    ///   obligation.
    /// * **Refcount:** neither `clRetainMemObject` nor
    ///   `clRetainCommandQueue` is called here, and there is no `Drop`
    ///   that releases. The caller's references on *both* objects must
    ///   outlive this value and every [`Clone`] of it — pass a
    ///   `keep_alive` anchor that holds them, or carry the obligation
    ///   directly when it is `None`. Releasing either while a clone
    ///   survives is a use-after-free.
    /// * `row_pitch` is meaningful only when `mem` is a BUFFER object
    ///   holding image rows that are not tightly packed; it must then be
    ///   the real row stride in bytes, since consumers index rows by it.
    ///   Pass `0` for image objects and tightly-packed buffers.
    /// * **Cross-thread:** `OpenClMem` is `Send + Sync`. OpenCL objects
    ///   are thread-safe under the 1.2+ spec, but a single
    ///   `cl_command_queue` is only safe to enqueue on concurrently
    ///   because the runtime serialises it — the caller must still not
    ///   assume ordering between its own enqueues and the consumer's.
    pub unsafe fn try_from_raw(
        mem: *mut c_void,
        queue: *mut c_void,
        row_pitch: u32,
        keep_alive: Option<KeepAlive>,
    ) -> Result<Self, InvalidHandleError> {
        if mem.is_null() {
            return Err(InvalidHandleError::NullPointer("cl_mem"));
        }
        if queue.is_null() {
            return Err(InvalidHandleError::NullPointer("cl_command_queue"));
        }
        Ok(Self { mem, queue, row_pitch, keep_alive })
    }

    #[inline]
    pub fn mem(&self) -> *mut c_void {
        self.mem
    }
    #[inline]
    pub fn queue(&self) -> *mut c_void {
        self.queue
    }
    #[inline]
    pub fn row_pitch(&self) -> u32 {
        self.row_pitch
    }
    #[inline]
    pub fn keep_alive(&self) -> Option<&KeepAlive> {
        self.keep_alive.as_ref()
    }
}

impl fmt::Debug for OpenClMem {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("OpenClMem").field("row_pitch", &self.row_pitch).finish()
    }
}

unsafe impl Send for OpenClMem {}
unsafe impl Sync for OpenClMem {}

// ─────────────────────────────────────────────────────────────────────────────
// Metal
// ─────────────────────────────────────────────────────────────────────────────

/// `MTLTexture*` (Objective-C-bridged Metal texture).
#[derive(Clone)]
pub struct MetalTextureHandle {
    tex: *mut c_void,
    registry_id: Option<u64>,
    keep_alive: Option<KeepAlive>,
}

impl MetalTextureHandle {
    /// Wrap a raw `id<MTLTexture>`. *Borrowing*: the handle is stored
    /// non-owningly, this type has no [`Drop`], and every obligation below
    /// extends to each [`Clone`].
    ///
    /// # Safety
    ///
    /// * `tex` must be a live Objective-C object conforming to
    ///   `MTLTexture`. It is stored verbatim and consumers send Metal
    ///   selectors to it, so any other class is undefined behaviour.
    ///   Null is rejected as [`InvalidHandleError::NullPointer`] and is
    ///   not a caller obligation.
    /// * **Refcount:** no `retain` is issued here and there is no `Drop`
    ///   that would `release`. The producer's own strong reference must
    ///   outlive this value and every [`Clone`] of it — either by
    ///   parking that reference in the `keep_alive` anchor, or by the
    ///   caller keeping the owning `Retained<…>` / autorelease pool
    ///   alive itself when `keep_alive` is `None`. Because [`Clone`]
    ///   copies the bare `id` with no ARC traffic, an early `release`
    ///   leaves live clones pointing at a deallocated object.
    /// * `registry_id`, when `Some`, must be the owning `MTLDevice`'s
    ///   `registryID`; importers use it to refuse textures from a
    ///   different GPU than the wgpu device.
    /// * **Cross-thread:** `MetalTextureHandle` is `Send + Sync`.
    ///   `MTLTexture` instances are thread-safe per the Metal
    ///   specification and ARC retain counts are atomic, which is what
    ///   makes that sound. The caller must still not mutate the
    ///   texture's contents concurrently with the consumer's reads.
    pub unsafe fn try_from_raw(
        tex: *mut c_void,
        registry_id: Option<u64>,
        keep_alive: Option<KeepAlive>,
    ) -> Result<Self, InvalidHandleError> {
        if tex.is_null() {
            return Err(InvalidHandleError::NullPointer("MTLTexture"));
        }
        Ok(Self { tex, registry_id, keep_alive })
    }

    #[inline]
    pub fn texture(&self) -> *mut c_void {
        self.tex
    }
    #[inline]
    pub fn registry_id(&self) -> Option<u64> {
        self.registry_id
    }
    #[inline]
    pub fn keep_alive(&self) -> Option<&KeepAlive> {
        self.keep_alive.as_ref()
    }
}

impl fmt::Debug for MetalTextureHandle {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("MetalTextureHandle").field("registry_id", &self.registry_id).finish()
    }
}

// SAFETY: MTLTexture instances are thread-safe per Metal spec; ARC
// counts are atomic.
unsafe impl Send for MetalTextureHandle {}
unsafe impl Sync for MetalTextureHandle {}

/// `MTLBuffer*`.
#[derive(Clone)]
pub struct MetalBufferHandle {
    buf: *mut c_void,
    row_pitch: u32,
    registry_id: Option<u64>,
    keep_alive: Option<KeepAlive>,
}

impl MetalBufferHandle {
    /// Wrap a raw `id<MTLBuffer>`. *Borrowing*: the handle is stored
    /// non-owningly, this type has no [`Drop`], and every obligation below
    /// extends to each [`Clone`].
    ///
    /// # Safety
    ///
    /// * `buf` must be a live Objective-C object conforming to
    ///   `MTLBuffer`. Null is rejected as
    ///   [`InvalidHandleError::NullPointer`] and is not a caller
    ///   obligation.
    /// * `row_pitch` must be the real row stride in bytes when the
    ///   buffer carries image rows; consumers index rows by it, so an
    ///   under-sized value reads a shifted image and an over-sized one
    ///   runs off the end of `[MTLBuffer length]`.
    /// * Refcount, lifetime, `registry_id` and cross-thread obligations
    ///   are exactly those of [`MetalTextureHandle::try_from_raw`]: no
    ///   `retain`, no `Drop`, the producer's strong reference must
    ///   outlive every [`Clone`].
    pub unsafe fn try_from_raw(
        buf: *mut c_void,
        row_pitch: u32,
        registry_id: Option<u64>,
        keep_alive: Option<KeepAlive>,
    ) -> Result<Self, InvalidHandleError> {
        if buf.is_null() {
            return Err(InvalidHandleError::NullPointer("MTLBuffer"));
        }
        Ok(Self { buf, row_pitch, registry_id, keep_alive })
    }

    #[inline]
    pub fn buffer(&self) -> *mut c_void {
        self.buf
    }
    #[inline]
    pub fn row_pitch(&self) -> u32 {
        self.row_pitch
    }
    #[inline]
    pub fn registry_id(&self) -> Option<u64> {
        self.registry_id
    }
    #[inline]
    pub fn keep_alive(&self) -> Option<&KeepAlive> {
        self.keep_alive.as_ref()
    }
}

impl fmt::Debug for MetalBufferHandle {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("MetalBufferHandle")
            .field("row_pitch", &self.row_pitch)
            .field("registry_id", &self.registry_id)
            .finish()
    }
}

unsafe impl Send for MetalBufferHandle {}
unsafe impl Sync for MetalBufferHandle {}

// ─────────────────────────────────────────────────────────────────────────────
// Apple — IOSurface, VideoToolbox
// ─────────────────────────────────────────────────────────────────────────────

/// `IOSurfaceRef` with a CF-refcount-anchored lifetime. Clone bumps the
/// Arc, not CFRetain — the underlying `CFRetain` runs once at
/// construction.
///
/// # Lifetime: allocation vs. content
///
/// The two are separate obligations and this type discharges them with
/// two separate fields. Conflating them is the defect the `keep_alive`
/// slot exists to prevent.
///
/// * **Allocation** — that the `IOSurfaceRef` still names a live kernel
///   surface. `retain` discharges this unconditionally: one `CFRetain`
///   at construction, one `CFRelease` on the last clone's drop. No
///   caller action, no anchor, nothing to forget.
/// * **Content** — that nobody *else* is writing those pixels. A
///   `CFRetain` cannot express this: a producer that vends surfaces out
///   of a recycling ring can hand the same live surface to a second
///   writer the moment its slot's busy bit clears, and every holder's
///   retain stays perfectly valid while the pixels are overwritten
///   underneath them. The optional `keep_alive` discharges it: the
///   producer parks the slot's RAII lease here, every clone of the
///   carrier holds it, and the ring cannot re-issue the slot until the
///   last clone is gone.
///
/// `WgpuTexture` (feature `wgpu`) carries the identical split for the
/// identical reason — an internally-refcounted handle whose refcount
/// pins the allocation and whose `keep_alive` pins the content. A
/// producer that mints a fresh surface per call leaves this `None` and
/// owes nothing; a **pooled** producer must attach the lease via
/// [`Self::with_keep_alive`] or its consumers race the pool.
#[cfg(target_vendor = "apple")]
#[derive(Clone)]
pub struct IoSurface {
    handle: *mut c_void,
    retain: Arc<IoSurfaceRetain>,
    keep_alive: Option<KeepAlive>,
}

#[cfg(target_vendor = "apple")]
impl IoSurface {
    /// Wrap an `IOSurfaceRef`, taking one new CoreFoundation reference.
    /// *Refcount-owning*: the reference taken here is released on the last
    /// [`Clone`]'s drop.
    ///
    /// # Safety
    ///
    /// * `handle` must point to a live `IOSurface` and must still be
    ///   live *at the moment of this call*: the caller must hold a
    ///   reference it has not released. Null is rejected as
    ///   [`InvalidHandleError::NullPointer`] before the retain, so it is
    ///   not a caller obligation — but a dangling non-null pointer is
    ///   passed straight to `CFRetain`.
    /// * **Ownership is shared, not transferred.** One `CFRetain` is
    ///   taken here and released by the last `Arc<IoSurfaceRetain>`
    ///   drop; the caller's own reference is untouched and remains the
    ///   caller's to release whenever it likes, including immediately
    ///   after this returns. [`Clone`] bumps only the `Arc`, never
    ///   CoreFoundation.
    /// * The caller must **not** `CFRelease` on this value's behalf. The
    ///   surface stays alive for the whole lifetime of every clone
    ///   without any further action, so **no anchor is needed to keep
    ///   the allocation live**. That is the only obligation the retain
    ///   discharges: if `handle` came out of a recycling pool, the
    ///   *content* obligation is still open and the producer must attach
    ///   the slot's lease with [`Self::with_keep_alive`] — see the
    ///   type's `# Lifetime` section.
    /// * No thread affinity: `IOSurface` is designed for cross-process
    ///   sharing and its CoreFoundation refcount is atomic, which is
    ///   what backs the `unsafe impl Send + Sync` below. Concurrent
    ///   *access to the pixels* still needs `IOSurfaceLock` /
    ///   `IOSurfaceUnlock` or GPU-side synchronisation, which this type
    ///   does not provide.
    pub unsafe fn try_from_raw(handle: *mut c_void) -> Result<Self, InvalidHandleError> {
        if handle.is_null() {
            return Err(InvalidHandleError::NullPointer("IOSurfaceRef"));
        }
        // SAFETY: caller invariant.
        let retain = Arc::new(unsafe { IoSurfaceRetain::new(handle) });
        Ok(Self { handle, retain, keep_alive: None })
    }

    /// Attach the producer's keep-alive anchor — typically the RAII
    /// lease of the pool / ring slot this surface *is*. Held by this
    /// value and by every [`Clone`] of it (and therefore of the
    /// enclosing [`GpuResource`](crate::GpuResource)); the producer's
    /// pool may recycle the slot only once the last holder drops.
    ///
    /// **Mandatory for a pooled producer.** Without it the pool clears
    /// the slot's busy bit as soon as its own lease goes out of scope,
    /// while consumers still hold live carriers whose `CFRetain` keeps
    /// the surface alive — so the next acquire of the same shape hands
    /// the same surface to a second writer and the corruption is
    /// silent (two writers, one surface, no synchronisation between
    /// them) rather than a crash. Producers that mint a fresh surface
    /// per call leave it unset.
    #[inline]
    #[must_use]
    pub fn with_keep_alive(mut self, keep_alive: KeepAlive) -> Self {
        self.keep_alive = Some(keep_alive);
        self
    }

    #[inline]
    pub fn handle(&self) -> *mut c_void {
        self.handle
    }
    #[inline]
    pub fn retain(&self) -> &Arc<IoSurfaceRetain> {
        &self.retain
    }
    /// The producer's keep-alive anchor, when one was attached. `None`
    /// for a fresh-minted surface, which owes nothing.
    #[inline]
    pub fn keep_alive(&self) -> Option<&KeepAlive> {
        self.keep_alive.as_ref()
    }
}

#[cfg(target_vendor = "apple")]
impl fmt::Debug for IoSurface {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("IoSurface").field("keep_alive", &self.keep_alive.is_some()).finish_non_exhaustive()
    }
}

#[cfg(target_vendor = "apple")]
unsafe impl Send for IoSurface {}
#[cfg(target_vendor = "apple")]
unsafe impl Sync for IoSurface {}

/// VideoToolbox `CVPixelBufferRef` with a CV-refcount-anchored lifetime.
///
/// # Lifetime: allocation vs. content
///
/// Identical split to [`IoSurface`], for the identical reason, and the
/// two Apple carriers discharge it identically.
///
/// * **Allocation** — that the `CVPixelBufferRef` still names a live
///   buffer. `retain` discharges this unconditionally: one
///   `CVBufferRetain` at construction, one `CVBufferRelease` on the last
///   clone's drop.
/// * **Content** — that nobody *else* is writing those pixels. A
///   `CVBufferRetain` cannot express it: a producer that vends buffers
///   out of a recycling ring (an encoder-input pixel-buffer pool, say)
///   can hand the same live buffer to a second writer the moment its
///   slot's busy bit clears, while every holder's retain stays perfectly
///   valid. The optional `keep_alive` discharges it — the producer parks
///   the slot's RAII lease here and the ring cannot re-issue the slot
///   until the last clone of the carrier is gone.
///
/// Without the `keep_alive` slot a pooled producer's lease would be
/// pinned **only** by whatever wrapper it returned the carrier in: a
/// consumer that cloned the carrier out of that wrapper and dropped the
/// wrapper would hold a carrier whose slot was already recyclable.
/// [`IoSurface`] carries the anchor for the same reason.
#[cfg(target_vendor = "apple")]
#[derive(Clone)]
pub struct VideoToolboxFrame {
    pixel_buffer: *mut c_void,
    retain: Arc<CvBufferRetain>,
    keep_alive: Option<KeepAlive>,
}

#[cfg(target_vendor = "apple")]
impl VideoToolboxFrame {
    /// Wrap a `CVPixelBufferRef`, taking one new CoreVideo reference.
    /// *Refcount-owning*: the reference taken here is released on the last
    /// [`Clone`]'s drop.
    ///
    /// # Safety
    ///
    /// * `pixel_buffer` must point to a live `CVPixelBuffer` and must
    ///   still be live *at the moment of this call*: the caller must
    ///   hold a reference it has not released. Null is rejected as
    ///   [`InvalidHandleError::NullPointer`] before the retain, so it is
    ///   not a caller obligation — but a dangling non-null pointer is
    ///   passed straight to `CVBufferRetain`.
    /// * **Ownership is shared, not transferred.** One `CVBufferRetain`
    ///   is taken here and released by the last `Arc<CvBufferRetain>`
    ///   drop. The caller's own reference is untouched — a
    ///   VideoToolbox decoder callback may therefore release its
    ///   `CVPixelBufferRef` as soon as this returns. [`Clone`] bumps
    ///   only the `Arc`.
    /// * The caller must **not** issue a `CVBufferRelease` on this
    ///   value's behalf.
    /// * No thread affinity: CoreVideo refcounts are atomic, which is
    ///   what backs the `unsafe impl Send + Sync` below. Reading the
    ///   *pixels* from the CPU still requires
    ///   `CVPixelBufferLockBaseAddress`, which this type does not do.
    /// * The retain keeps the **allocation** live and nothing more. If
    ///   `pixel_buffer` came out of a recycling pool, the *content*
    ///   obligation is still open and the producer must attach the
    ///   slot's lease with [`Self::with_keep_alive`] — see the type's
    ///   `# Lifetime` section.
    pub unsafe fn try_from_raw(pixel_buffer: *mut c_void) -> Result<Self, InvalidHandleError> {
        if pixel_buffer.is_null() {
            return Err(InvalidHandleError::NullPointer("CVPixelBufferRef"));
        }
        // SAFETY: caller invariant.
        let retain = Arc::new(unsafe { CvBufferRetain::new(pixel_buffer) });
        Ok(Self { pixel_buffer, retain, keep_alive: None })
    }

    /// Attach the producer's keep-alive anchor — typically the RAII
    /// lease of the pool / ring slot this pixel buffer *is*. Held by
    /// this value and by every [`Clone`] of it (and therefore of the
    /// enclosing [`GpuResource`](crate::GpuResource)); the producer's
    /// pool may recycle the slot only once the last holder drops.
    ///
    /// **Mandatory for a pooled producer**, for exactly the reason
    /// [`IoSurface::with_keep_alive`] states: without it the pool clears
    /// the slot's busy bit as soon as its own lease goes out of scope
    /// while consumers still hold live carriers whose `CVBufferRetain`
    /// keeps the buffer alive — so the next acquire of the same shape
    /// hands the same buffer to a second writer, silently.
    #[inline]
    #[must_use]
    pub fn with_keep_alive(mut self, keep_alive: KeepAlive) -> Self {
        self.keep_alive = Some(keep_alive);
        self
    }

    #[inline]
    pub fn pixel_buffer(&self) -> *mut c_void {
        self.pixel_buffer
    }
    #[inline]
    pub fn retain(&self) -> &Arc<CvBufferRetain> {
        &self.retain
    }
    /// The producer's keep-alive anchor, when one was attached. `None`
    /// for a buffer that is not pool-vended, which owes nothing.
    #[inline]
    pub fn keep_alive(&self) -> Option<&KeepAlive> {
        self.keep_alive.as_ref()
    }
}

#[cfg(target_vendor = "apple")]
impl fmt::Debug for VideoToolboxFrame {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("VideoToolboxFrame").field("keep_alive", &self.keep_alive.is_some()).finish_non_exhaustive()
    }
}

#[cfg(target_vendor = "apple")]
unsafe impl Send for VideoToolboxFrame {}
#[cfg(target_vendor = "apple")]
unsafe impl Sync for VideoToolboxFrame {}

// ─────────────────────────────────────────────────────────────────────────────
// OpenGL
// ─────────────────────────────────────────────────────────────────────────────

/// GL texture name (`GLuint`) + binding metadata.
#[derive(Clone)]
pub struct GlTextureHandle {
    name: u32,
    target: super::GlTextureTarget,
    format: super::GlInternalFormat,
    context: *mut c_void,
    share_group: Option<u64>,
    keep_alive: Option<KeepAlive>,
}

impl GlTextureHandle {
    /// Wrap a GL texture name plus its binding metadata. *Borrowing*: the
    /// handle is stored non-owningly, this type has no [`Drop`], and every
    /// obligation below extends to each [`Clone`].
    ///
    /// # Safety
    ///
    /// * `name` must be a texture name that is live in `context`'s share
    ///   group — allocated by `glGenTextures`/`glCreateTextures` and not
    ///   yet deleted. GL names are small integers, so an arbitrary `u32`
    ///   is not distinguishable from a real one at the API boundary and
    ///   will silently address whatever texture the driver later assigns
    ///   that name. `name == 0` is rejected as
    ///   [`InvalidHandleError::NullHandle`] and is not a caller
    ///   obligation.
    /// * `target` and `format` must be the texture's actual binding
    ///   target and sized internal format. Consumers bind with `target`
    ///   and interpret texels by `format`; a mismatched `target` is a
    ///   GL error, a mismatched `format` misreads the texel data.
    /// * `context == null` means "whatever context is current on the
    ///   consuming thread". That is sound **only** in a single-context
    ///   process, or when the caller has independently guaranteed the
    ///   consumer runs on a thread with a context in the right share
    ///   group. Otherwise pass the real context handle.
    /// * `share_group`, when `Some`, must identify the share group
    ///   `name` belongs to; importers use it to refuse names from an
    ///   unrelated group.
    /// * **Thread affinity — this is the sharp edge.** GL contexts are
    ///   current on at most one thread at a time and texture names are
    ///   only meaningful to a thread whose current context is in the
    ///   same share group. `GlTextureHandle` is nevertheless `Send +
    ///   Sync`, because the *handle* is inert data; the caller asserts
    ///   that whichever thread ultimately touches it has an appropriate
    ///   context current, and that the producer is not concurrently
    ///   issuing GL commands against the same name from another.
    /// * Lifetime: nothing is retained and there is no `Drop`, so
    ///   `glDeleteTextures` must not run while this value or any
    ///   [`Clone`] of it is reachable. Pass a `keep_alive` anchor to
    ///   discharge that; with `None` the caller carries it.
    pub unsafe fn try_from_raw(
        name: u32,
        target: super::GlTextureTarget,
        format: super::GlInternalFormat,
        context: *mut c_void,
        share_group: Option<u64>,
        keep_alive: Option<KeepAlive>,
    ) -> Result<Self, InvalidHandleError> {
        if name == 0 {
            return Err(InvalidHandleError::NullHandle("GL texture name"));
        }
        Ok(Self { name, target, format, context, share_group, keep_alive })
    }

    #[inline]
    pub fn name(&self) -> u32 {
        self.name
    }
    #[inline]
    pub fn target(&self) -> super::GlTextureTarget {
        self.target
    }
    #[inline]
    pub fn format(&self) -> super::GlInternalFormat {
        self.format
    }
    #[inline]
    pub fn context(&self) -> *mut c_void {
        self.context
    }
    #[inline]
    pub fn share_group(&self) -> Option<u64> {
        self.share_group
    }
    #[inline]
    pub fn keep_alive(&self) -> Option<&KeepAlive> {
        self.keep_alive.as_ref()
    }
}

impl fmt::Debug for GlTextureHandle {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("GlTextureHandle")
            .field("name", &self.name)
            .field("target", &self.target)
            .field("format", &self.format)
            .field("share_group", &self.share_group)
            .finish()
    }
}

unsafe impl Send for GlTextureHandle {}
unsafe impl Sync for GlTextureHandle {}

/// GL buffer object (`GLuint`) + binding metadata.
#[derive(Clone)]
pub struct GlBufferHandle {
    name: u32,
    target: super::GlBufferTarget,
    size: u64,
    context: *mut c_void,
    share_group: Option<u64>,
    keep_alive: Option<KeepAlive>,
}

impl GlBufferHandle {
    /// Wrap a GL buffer-object name plus its binding metadata. *Borrowing*:
    /// the handle is stored non-owningly, this type has no [`Drop`], and
    /// every obligation below extends to each [`Clone`].
    ///
    /// # Safety
    ///
    /// * `name` must be a buffer-object name live in `context`'s share
    ///   group, and `target` its actual binding target.
    /// * `size` must not exceed the buffer's real store size in bytes —
    ///   consumers read and write `[0, size)` through it. Zero is
    ///   rejected as [`InvalidHandleError::ZeroSize`] and `name == 0` as
    ///   [`InvalidHandleError::NullHandle`]; neither is a caller
    ///   obligation.
    /// * The `context == null` meaning, the `share_group` obligation,
    ///   the thread-affinity assertion and the lifetime rule (no retain,
    ///   no `Drop`, no `glDeleteBuffers` while any [`Clone`] is
    ///   reachable) are exactly those of
    ///   [`GlTextureHandle::try_from_raw`].
    pub unsafe fn try_from_raw(
        name: u32,
        target: super::GlBufferTarget,
        size: u64,
        context: *mut c_void,
        share_group: Option<u64>,
        keep_alive: Option<KeepAlive>,
    ) -> Result<Self, InvalidHandleError> {
        if name == 0 {
            return Err(InvalidHandleError::NullHandle("GL buffer name"));
        }
        if size == 0 {
            return Err(InvalidHandleError::ZeroSize("GL buffer"));
        }
        Ok(Self { name, target, size, context, share_group, keep_alive })
    }

    #[inline]
    pub fn name(&self) -> u32 {
        self.name
    }
    #[inline]
    pub fn target(&self) -> super::GlBufferTarget {
        self.target
    }
    #[inline]
    pub fn size(&self) -> u64 {
        self.size
    }
    #[inline]
    pub fn context(&self) -> *mut c_void {
        self.context
    }
    #[inline]
    pub fn share_group(&self) -> Option<u64> {
        self.share_group
    }
    #[inline]
    pub fn keep_alive(&self) -> Option<&KeepAlive> {
        self.keep_alive.as_ref()
    }
}

impl fmt::Debug for GlBufferHandle {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("GlBufferHandle")
            .field("name", &self.name)
            .field("target", &self.target)
            .field("size", &self.size)
            .field("share_group", &self.share_group)
            .finish()
    }
}

unsafe impl Send for GlBufferHandle {}
unsafe impl Sync for GlBufferHandle {}

// ─────────────────────────────────────────────────────────────────────────────
// DMA-BUF (Linux / Android)
// ─────────────────────────────────────────────────────────────────────────────

/// Linux / Android DMA-BUF descriptor — the direct analogue of libva's
/// [`VADRMPRIMESurfaceDescriptor`] (`va_drmcommon.h`).
///
/// # Object / plane model (mirrors `VADRMPRIMESurfaceDescriptor`)
///
/// A surface is `M` DRM **objects** (fds) carrying `N` **planes**. libva's
/// descriptor splits this into `objects[]` (fd + size + modifier) and
/// `layers[]` (each a `drm_format` + planes, every plane naming its
/// `object_index`, `offset`, `pitch`). This type flattens the layer/plane nesting
/// into one per-plane view — every plane names the object (fd) it lives in
/// via [`Self::plane_object_index`], plus its [`Self::plane_offsets`] and
/// [`Self::plane_strides`] (libva `pitch`):
///
/// - [`Self::fds`] — the `objects[]` fds, `M` of them (`≤ 4`, the libva
///   `objects[4]` cap). Single-object NV12/P010 (the `COMPOSED_LAYERS`
///   export common case) has `M = 1` with every plane at object index 0.
/// - [`Self::modifier`] — the DRM format modifier. libva stores it
///   per-object, but a surface's tiling is uniform across its objects and
///   the Vulkan importer takes a **single** `drmFormatModifier` per
///   `VkImage` (`VkImageDrmFormatModifierExplicitCreateInfoEXT`), so one
///   modifier describes the whole surface.
/// - [`Self::num_planes`] / [`Self::plane_object_index`] /
///   [`Self::plane_offsets`] / [`Self::plane_strides`] — the flattened
///   `layers[].{num_planes, object_index, offset, pitch}`.
///
/// The model therefore covers `N` planes across `M` objects, not just the
/// single-fd / single-object NV12 case.
///
/// **Import capacity note:** a single-`VkImage` importer with an import
/// cache keyed on the primary fd number supports
/// only **single-object** surfaces (`M = 1`, every plane at object index
/// 0) — the `COMPOSED_LAYERS` NV12/P010 export common case. `M > 1`
/// (`fds.len() > 1` / distinct `plane_object_index`) is capacity in the
/// carrier that such an importer cannot consume: it needs a `DISJOINT`
/// multi-memory-plane import path and a multi-fd cache key, and without
/// them it rejects a multi-object handle. A producer must not emit one
/// expecting it to import there.
///
/// # FD discipline (dup once, Arc-share every emission)
///
/// [`Self::fds`] are `Arc<OwnedFd>`: `Clone` is an `Arc` refcount bump, and
/// the last drop closes each fd via std's `OwnedFd::drop`. A frame-pool
/// producer **dup(2)s each object fd exactly once** when the slot is built
/// and Arc-shares it into every per-frame carrier — a per-emission `dup()`
/// is a bug, not a nicety, because an import cache keyed on the raw fd
/// *number* sees a fresh dup as a new number, misses, and forces a new
/// `VkImage` per frame. Emission never re-dups.
/// Ownership-transferring importers still dup per the module-level
/// "FD/handle
/// consumer rule"; that dup is the driver's private copy and does not
/// perturb the cache-identity fd this carrier holds.
///
/// # `keep_alive` — pool-slot pinning
///
/// [`Self::keep_alive`] pins the producer's recyclable pool slot (mirrors
/// `VaapiSurface::keep_alive` on Linux) so the slot cannot be re-issued — and its
/// backing memory overwritten — while a consumer-side clone of this handle
/// is still live. **Invariant:** the handle must be held until the submit
/// that samples the imported texture has been *made* (not retired); the
/// standard playback ring-of-1 lease honours this. The import path invokes
/// [`ResourceKeepAlive::mark_consumed`] after a successful import, which a
/// pool anchor overrides to flip its "imported" flag and switch to the
/// GPU-completion (rather than instant) recycle path.
///
/// # `acquire_release` — recycle-gate back-pressure
///
/// [`Self::acquire_release`] carries the consumer→producer slot-release
/// gate (the shared [`VkSlotRelease`] protocol; see its docs). A ring-pool
/// producer stamps it with the *previous* emission's `{gate, value}` so the
/// consumer's `on_submitted_work_done` can publish "prior read retired"
/// before the producer overwrites the slot. `None` for single-shot
/// (non-recycling) producers where no reuse race exists.
///
/// [`VADRMPRIMESurfaceDescriptor`]: https://intel.github.io/libva/structVADRMPRIMESurfaceDescriptor.html
#[cfg(any(target_os = "linux", target_os = "android"))]
#[derive(Clone)]
pub struct DmaBufHandle {
    /// DRM objects (fds), `1..=4`. libva `objects[]`. Index 0 is the
    /// primary object and the cache-identity anchor ([`Self::fd`]).
    fds: SmallVec<[Arc<OwnedFd>; 2]>,
    /// Validated against `fds` at construction and never re-exposed
    /// mutably — see [`DmaBufImportDesc`]. Read back field-by-field
    /// through [`Self::fourcc`], [`Self::modifier`], … or whole via
    /// [`Self::desc`].
    desc: DmaBufImportDesc,
    keep_alive: Option<KeepAlive>,
    acquire_release: Option<VkSlotRelease>,
}

/// Everything about a DMA-BUF surface except the object fds themselves —
/// the layout half of [`DmaBufHandle`].
///
/// One field per attribute a DMA-BUF importer reads, so a construction
/// site reads as the API it feeds: the
/// `EGL_EXT_image_dma_buf_import(_modifiers)` attribute list, libva's
/// [`VADRMPRIMESurfaceDescriptor`], or
/// `VkImageDrmFormatModifierExplicitCreateInfoEXT` +
/// `VkSubresourceLayout[]`. Every field's object/plane model, and why
/// one `modifier` covers a whole surface, is documented on
/// [`DmaBufHandle`] itself.
///
/// # Why plain `pub` fields
///
/// The descriptor is inert layout data — `vkImportMemoryFdKHR` and
/// `EGL_EXT_image_dma_buf_import` take it at face value, and getting it
/// wrong yields wrong pixels or a driver-side import error, never
/// undefined behaviour (see [`DmaBufHandle::new`]'s *Correctness, not
/// safety* note). The invariants that are checkable in-process — extent
/// non-degenerate, `1..=4` planes, every active plane naming a real
/// object — are checked by [`DmaBufHandle::from_objects`], the single
/// funnel every carrier is built through, against the `fds` it is paired
/// with. The carrier then stores the descriptor **privately**, so a
/// validated handle cannot be edited back into an invalid one.
///
/// [`VADRMPRIMESurfaceDescriptor`]: https://intel.github.io/libva/structVADRMPRIMESurfaceDescriptor.html
#[cfg(any(target_os = "linux", target_os = "android"))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct DmaBufImportDesc {
    /// DRM `FOURCC` of the surface (`DRM_FORMAT_NV12`, `DRM_FORMAT_ABGR8888`,
    /// …). libva `layers[].drm_format`.
    pub fourcc: u32,
    /// DRM format modifier describing the tiling / compression of the
    /// whole surface (`DRM_FORMAT_MOD_LINEAR` for the untiled case).
    /// One value per surface, not per object — see [`DmaBufHandle`].
    pub modifier: u64,
    /// Surface width in pixels. Rejected when zero.
    pub width: u32,
    /// Surface height in pixels. Rejected when zero.
    pub height: u32,
    /// Number of meaningful planes, `1..=4`. Bounds how far
    /// [`Self::plane_object_index`] / [`Self::plane_strides`] /
    /// [`Self::plane_offsets`] are read. Rejected outside `1..=4`.
    pub num_planes: u8,
    /// Object each plane lives in — index into [`DmaBufHandle::fds`].
    /// libva `layers[].object_index[]`. Only the first
    /// [`Self::num_planes`] entries are meaningful; each must name a real
    /// object or construction is rejected. `[0; 4]` for the
    /// single-object (`COMPOSED_LAYERS`) case that
    /// [`DmaBufHandle::new`] serves.
    pub plane_object_index: [u8; 4],
    /// Per-plane row stride in bytes (libva `layers[].pitch[]`). Only the
    /// first [`Self::num_planes`] entries are meaningful.
    pub plane_strides: [u32; 4],
    /// Per-plane byte offset within its object (libva
    /// `layers[].offset[]`). Only the first [`Self::num_planes`] entries
    /// are meaningful.
    pub plane_offsets: [u32; 4],
}

#[cfg(any(target_os = "linux", target_os = "android"))]
impl DmaBufHandle {
    /// Single-object constructor — every plane lives in one fd (the
    /// `COMPOSED_LAYERS` NV12/P010 case and every RGBA/BGRA/R/Rg surface).
    /// Adopts a freshly-minted `OwnedFd` (e.g. from `vkGetMemoryFdKHR`);
    /// `keep_alive` / `acquire_release` default to `None` (attach via
    /// [`Self::with_keep_alive`] / [`Self::with_acquire_release`]).
    ///
    /// # Correctness, not safety
    ///
    /// This constructor is deliberately **safe**, unlike every other
    /// entry point in this module: `fd` arrives as an [`OwnedFd`], so
    /// ownership and validity are already carried by the type system,
    /// and the layout arguments are inert data that the kernel bounds
    /// when the buffer is finally mapped. Getting them wrong therefore
    /// yields wrong pixels or a driver-side import error, not undefined
    /// behaviour, so there is no safety contract to state here.
    ///
    /// It is still a precondition of a *correct* import that `fd` name a
    /// real DMA-BUF and that `desc` describe its actual storage —
    /// `vkImportMemoryFdKHR` and `EGL_EXT_image_dma_buf_import` take it
    /// at face value.
    ///
    /// # Errors
    ///
    /// Delegates to [`Self::from_objects`], so a `desc` naming any object
    /// other than the single `fd` (a non-zero
    /// [`DmaBufImportDesc::plane_object_index`] entry within
    /// `num_planes`) is rejected as `plane_object_index` rather than
    /// silently coerced.
    pub fn new(fd: OwnedFd, desc: DmaBufImportDesc) -> Result<Self, InvalidHandleError> {
        let mut fds: SmallVec<[Arc<OwnedFd>; 2]> = SmallVec::new();
        fds.push(Arc::new(fd));
        Self::from_objects(fds, desc)
    }

    /// General multi-object constructor from pre-shared `Arc<OwnedFd>`s —
    /// the frame-pool emission path (fds already dup'd once at slot build,
    /// Arc-shared here per the type's "FD discipline").
    /// `desc.plane_object_index` names the object (index into `fds`) for
    /// each of the first `desc.num_planes` planes. `keep_alive` /
    /// `acquire_release` default to `None`; attach via the builders.
    ///
    /// Safe for the same reason as [`Self::new`] — see its
    /// *Correctness, not safety* note. The same import-correctness
    /// precondition applies to every fd in `fds` and to the layout
    /// arrays that index them.
    ///
    /// # Errors
    ///
    /// This is the single funnel every carrier is built through, and the
    /// only place `desc` is cross-checked against the objects it
    /// describes: degenerate extent, `num_planes` outside `1..=4`,
    /// `fds.len()` outside `1..=4` (libva's `objects[4]` cap), or an
    /// active plane naming an object that does not exist.
    pub fn from_objects(fds: SmallVec<[Arc<OwnedFd>; 2]>, desc: DmaBufImportDesc) -> Result<Self, InvalidHandleError> {
        if desc.width == 0 || desc.height == 0 {
            return Err(InvalidHandleError::InvalidValue { field: "DMA-BUF extent" });
        }
        if desc.num_planes == 0 || desc.num_planes > 4 {
            return Err(InvalidHandleError::InvalidValue { field: "num_planes" });
        }
        // libva caps `objects[4]`; every surface has ≥ 1 object.
        if fds.is_empty() || fds.len() > 4 {
            return Err(InvalidHandleError::InvalidValue { field: "num_objects" });
        }
        // Every active plane must reference a real object.
        for &obj in &desc.plane_object_index[..desc.num_planes as usize] {
            if obj as usize >= fds.len() {
                return Err(InvalidHandleError::InvalidValue { field: "plane_object_index" });
            }
        }
        Ok(Self { fds, desc, keep_alive: None, acquire_release: None })
    }

    /// Attach a pool-slot keep-alive — see the type-level `keep_alive` doc.
    #[inline]
    pub fn with_keep_alive(mut self, keep_alive: KeepAlive) -> Self {
        self.keep_alive = Some(keep_alive);
        self
    }

    /// Attach the consumer→producer slot-release gate — see the type-level
    /// `acquire_release` doc and [`VkSlotRelease`].
    #[inline]
    pub fn with_acquire_release(mut self, release: VkSlotRelease) -> Self {
        self.acquire_release = Some(release);
        self
    }

    /// Primary object fd (`fds[0]`) — the raw-fd-number cache-identity
    /// anchor and the fd used by the single-object import paths. Never
    /// empty (constructors reject a zero-object descriptor).
    #[inline]
    pub fn fd(&self) -> &Arc<OwnedFd> {
        &self.fds[0]
    }
    /// All DRM object fds (libva `objects[]`), `1..=4`.
    #[inline]
    pub fn fds(&self) -> &[Arc<OwnedFd>] {
        &self.fds
    }
    /// The whole validated layout descriptor, as handed to
    /// [`Self::from_objects`]. Re-emitting a carrier over a `dup`ed fd
    /// is `DmaBufHandle::new(dup, *src.desc())` — no field-by-field
    /// re-assembly, so a new descriptor field cannot be silently
    /// dropped on the way through. Importers that need the whole layout
    /// (`EGL_EXT_image_dma_buf_import_modifiers` attribute assembly,
    /// `VkSubresourceLayout[]` fill-in) take this rather than a dozen
    /// per-field calls.
    #[inline]
    pub fn desc(&self) -> &DmaBufImportDesc {
        &self.desc
    }
    #[inline]
    pub fn fourcc(&self) -> u32 {
        self.desc.fourcc
    }
    #[inline]
    pub fn modifier(&self) -> u64 {
        self.desc.modifier
    }
    #[inline]
    pub fn width(&self) -> u32 {
        self.desc.width
    }
    #[inline]
    pub fn height(&self) -> u32 {
        self.desc.height
    }
    #[inline]
    pub fn num_planes(&self) -> u8 {
        self.desc.num_planes
    }
    /// Object index (into [`Self::fds`]) for each plane — libva
    /// `layers[].object_index[]`. Only the first [`Self::num_planes`]
    /// entries are meaningful.
    #[inline]
    pub fn plane_object_index(&self) -> [u8; 4] {
        self.desc.plane_object_index
    }
    #[inline]
    pub fn plane_strides(&self) -> [u32; 4] {
        self.desc.plane_strides
    }
    #[inline]
    pub fn plane_offsets(&self) -> [u32; 4] {
        self.desc.plane_offsets
    }
    /// Pool-slot keep-alive set via [`Self::with_keep_alive`].
    #[inline]
    pub fn keep_alive(&self) -> Option<&KeepAlive> {
        self.keep_alive.as_ref()
    }
    /// Consumer→producer slot-release gate set via
    /// [`Self::with_acquire_release`]. See [`VkSlotRelease`].
    #[inline]
    pub fn acquire_release(&self) -> Option<&VkSlotRelease> {
        self.acquire_release.as_ref()
    }
}

#[cfg(any(target_os = "linux", target_os = "android"))]
impl fmt::Debug for DmaBufHandle {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        use std::os::fd::AsRawFd;
        let raw_fds: SmallVec<[i32; 2]> = self.fds.iter().map(|fd| fd.as_raw_fd()).collect();
        f.debug_struct("DmaBufHandle")
            .field("fds", &raw_fds)
            .field("desc", &self.desc)
            .field("keep_alive", &self.keep_alive.is_some())
            .field("acquire_release", &self.acquire_release.is_some())
            .finish()
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Android
// ─────────────────────────────────────────────────────────────────────────────

/// `AHardwareBuffer*` with refcount-anchored lifetime via [`AHbInner`].
#[cfg(target_os = "android")]
#[derive(Clone)]
pub struct AHardwareBufferHandle {
    inner: Arc<AHbInner>,
}

#[cfg(target_os = "android")]
impl AHardwareBufferHandle {
    /// Wrap an `AHardwareBuffer*`, taking one new reference via
    /// `AHardwareBuffer_acquire`. *Refcount-owning*: the reference taken
    /// here is released on the last [`Clone`]'s drop.
    ///
    /// # Safety
    ///
    /// * `handle` must point to a live `AHardwareBuffer` on which the
    ///   caller currently holds a reference. Use this for **borrowed**
    ///   handles — an `AImage_getHardwareBuffer` result, a
    ///   `MediaCodec` output buffer, a gralloc handle owned by someone
    ///   else — where the reference stays with its original owner.
    /// * **Ownership is shared, not transferred.** The `+1` taken here
    ///   is released by the last `Arc<AHbInner>` drop; the caller's
    ///   reference is untouched and remains the caller's to release.
    ///   [`Clone`] bumps only the `Arc`, never gralloc.
    /// * The caller must not issue the balancing
    ///   `AHardwareBuffer_release` for the reference taken here.
    /// * Null is rejected as [`InvalidHandleError::NullHandle`], so it
    ///   is not a caller obligation.
    /// * No thread affinity — `AHardwareBuffer` refcounts are atomic and
    ///   the buffer is meant for cross-process sharing. Concurrent
    ///   *access to the pixels* still needs the usual fence or
    ///   `AHardwareBuffer_lock` discipline, which this type does not
    ///   provide.
    pub unsafe fn acquire(handle: *mut ndk_sys::AHardwareBuffer) -> Result<Self, InvalidHandleError> {
        // SAFETY: caller invariant.
        let inner = Arc::new(unsafe { AHbInner::acquire(handle)? });
        Ok(Self { inner })
    }

    /// Wrap an `AHardwareBuffer*` by **adopting** a reference the caller
    /// already holds. No `AHardwareBuffer_acquire` is issued.
    /// *Refcount-owning*: the adopted reference is released on the last
    /// [`Clone`]'s drop.
    ///
    /// # Safety
    ///
    /// * `handle` must point to a live `AHardwareBuffer` on which the
    ///   caller holds a reference it has **not** yet released — one it
    ///   took itself via `AHardwareBuffer_allocate`,
    ///   `AHardwareBuffer_acquire`, or a `recvBuffer`/`fromHardwareBuffer`
    ///   call that returned an owned reference.
    /// * **That reference is transferred here.** The caller must never
    ///   release it: the single balancing `AHardwareBuffer_release` is
    ///   issued by the last `Arc<AHbInner>` drop, so a caller-side
    ///   release is a double-free of a refcount shared across processes.
    /// * Conversely, passing a **borrowed** handle under-counts the
    ///   buffer — `Drop` will release a reference that was never taken,
    ///   freeing it out from under its real owner. Use [`Self::acquire`]
    ///   for borrowed handles.
    /// * Null is rejected as [`InvalidHandleError::NullHandle`], so it
    ///   is not a caller obligation.
    /// * No thread affinity, as for [`Self::acquire`].
    pub unsafe fn from_acquired(handle: *mut ndk_sys::AHardwareBuffer) -> Result<Self, InvalidHandleError> {
        // SAFETY: caller invariant.
        let inner = Arc::new(unsafe { AHbInner::from_acquired(handle)? });
        Ok(Self { inner })
    }

    #[inline]
    pub fn as_ptr(&self) -> *mut ndk_sys::AHardwareBuffer {
        self.inner.as_ptr()
    }
    #[inline]
    pub fn inner(&self) -> &Arc<AHbInner> {
        &self.inner
    }
}

#[cfg(target_os = "android")]
impl fmt::Debug for AHardwareBufferHandle {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("AHardwareBufferHandle").field("handle", &self.inner.as_ptr()).finish()
    }
}

/// MediaCodec decoder output frame in SurfaceTexture-backed mode.
#[cfg(target_os = "android")]
#[derive(Clone)]
pub struct MediaCodecFrame {
    buffer: *mut c_void,
    surface_texture: *mut c_void,
    format: PixelFormat,
    width: u32,
    height: u32,
    serial: u64,
    keep_alive: Option<KeepAlive>,
}

#[cfg(target_os = "android")]
impl MediaCodecFrame {
    /// Wrap a MediaCodec output buffer together with the `SurfaceTexture`
    /// it will be rendered into. *Borrowing*: the handle is stored
    /// non-owningly, this type has no [`Drop`], and every obligation below
    /// extends to each [`Clone`].
    ///
    /// # Safety
    ///
    /// * `buffer` must point to a live, **not yet released** MediaCodec
    ///   output buffer — an `AVMediaCodecBuffer*` from FFmpeg's
    ///   `mediacodec` hwaccel, or the `AMediaCodecBufferInfo*` of an
    ///   NDK-dequeued output index. The import path hands it to
    ///   `av_mediacodec_release_buffer` / `AMediaCodec_releaseOutputBuffer`
    ///   with `render = true` to push the frame onto the surface, so a
    ///   buffer that was already released is a double release. Null is
    ///   rejected as [`InvalidHandleError::NullPointer`] and is not a
    ///   caller obligation.
    /// * **Each buffer may be wrapped once.** Rendering is a one-shot
    ///   consuming act on the codec's side; because this newtype is
    ///   [`Clone`] and takes no ownership, two live carriers naming the
    ///   same `buffer` will each try to release it.
    /// * `surface_texture` must be a **JNI global reference** (not a
    ///   local ref, which is invalid outside the JNI frame that made it)
    ///   to the `android.graphics.SurfaceTexture` that backs the
    ///   `Surface` this codec was configured with. It is not null-checked
    ///   here.
    /// * `width`, `height` and `format` must describe the frame the
    ///   codec will render; the importer sizes its destination texture
    ///   from them.
    /// * **Thread affinity — the sharp edge.** `MediaCodecFrame` is
    ///   `Send + Sync`, but `SurfaceTexture.updateTexImage()` is only
    ///   legal on a thread with the OES texture's GL context current,
    ///   and only one `updateTexImage` may be in flight per texture.
    ///   The caller asserts the consumer will be driven from such a
    ///   thread, and that `serial` is monotonically increasing so the
    ///   importer can detect out-of-order or repeated presentation.
    /// * Lifetime: nothing is retained and there is no `Drop`. The
    ///   codec, its output surface and the `SurfaceTexture` global ref
    ///   must all outlive this value and every [`Clone`] of it —
    ///   `keep_alive` exists to anchor them.
    pub unsafe fn try_from_raw(
        buffer: *mut c_void,
        surface_texture: *mut c_void,
        format: PixelFormat,
        width: u32,
        height: u32,
        serial: u64,
        keep_alive: Option<KeepAlive>,
    ) -> Result<Self, InvalidHandleError> {
        if buffer.is_null() {
            return Err(InvalidHandleError::NullPointer("MediaCodec buffer"));
        }
        Ok(Self { buffer, surface_texture, format, width, height, serial, keep_alive })
    }

    #[inline]
    pub fn buffer(&self) -> *mut c_void {
        self.buffer
    }
    #[inline]
    pub fn surface_texture(&self) -> *mut c_void {
        self.surface_texture
    }
    #[inline]
    pub fn format(&self) -> PixelFormat {
        self.format
    }
    #[inline]
    pub fn width(&self) -> u32 {
        self.width
    }
    #[inline]
    pub fn height(&self) -> u32 {
        self.height
    }
    #[inline]
    pub fn serial(&self) -> u64 {
        self.serial
    }
    #[inline]
    pub fn keep_alive(&self) -> Option<&KeepAlive> {
        self.keep_alive.as_ref()
    }
}

#[cfg(target_os = "android")]
impl fmt::Debug for MediaCodecFrame {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("MediaCodecFrame")
            .field("format", &self.format)
            .field("width", &self.width)
            .field("height", &self.height)
            .field("serial", &self.serial)
            .finish()
    }
}

#[cfg(target_os = "android")]
unsafe impl Send for MediaCodecFrame {}
#[cfg(target_os = "android")]
unsafe impl Sync for MediaCodecFrame {}

/// `AImage*` with extracted AHB + per-frame metadata.
#[cfg(target_os = "android")]
#[derive(Clone)]
pub struct AImageFrame {
    image: *mut c_void,
    hardware: *mut c_void,
    timestamp_ns: i64,
    crop: Option<(i32, i32, i32, i32)>,
    format: PixelFormat,
    /// Caller-known color metadata for this frame, when the producer of the
    /// `AImageFrame` (e.g. a MediaCodec decoder that read `color-standard` /
    /// `color-range` off the output `MediaFormat` / container) knows the true
    /// color space. `None` when the producer cannot signal it (a bare Camera2 /
    /// MediaProjection consumer-surface pull).
    ///
    /// This is authoritative over the AHB driver's *suggested* YCbCr model on
    /// the compute-unpack import path: on some SoCs (Adreno 660) the driver
    /// suggests BT.601 for a MediaCodec `YUV_420_888` AHB regardless of the
    /// stream's real matrix, so trusting it decodes BT.709 content with the
    /// wrong matrix. An importer threads this into its import description so
    /// the unpack sampler is built with the caller's matrix + range instead.
    color: Option<video_types::ColorMetadata>,
    keep_alive: Option<KeepAlive>,
}

#[cfg(target_os = "android")]
impl AImageFrame {
    /// Wrap an `AImage*` together with the `AHardwareBuffer*` extracted
    /// from it. *Borrowing*: the handle is stored non-owningly, this type
    /// has no [`Drop`], and every obligation below extends to each
    /// [`Clone`].
    ///
    /// # Safety
    ///
    /// * `image` must point to a live `AImage` that has not been
    ///   `AImage_delete`d, and `hardware` to the `AHardwareBuffer*`
    ///   obtained from *that* `AImage` via
    ///   `AImage_getHardwareBuffer`. Both nulls are rejected as
    ///   [`InvalidHandleError::NullPointer`] and are not caller
    ///   obligations.
    /// * **`AImage_getHardwareBuffer` returns a borrowed pointer.** The
    ///   returned buffer's reference belongs to the `AImage` and is
    ///   invalidated by `AImage_delete`. Neither pointer is retained
    ///   here and there is no `Drop`, so `keep_alive` must hold whatever
    ///   keeps the `AImage` — and therefore the buffer — alive for the
    ///   lifetime of this value and every [`Clone`] of it. With
    ///   `keep_alive == None` the caller carries that directly.
    ///   Releasing the image while a clone survives is a use-after-free
    ///   in the importer.
    /// * `crop`, when `Some`, must be `(left, top, right, bottom)` from
    ///   `AImage_getCropRect` and must lie inside the buffer's
    ///   dimensions; consumers sample only that rectangle.
    /// * `format` must be the buffer's real layout and `timestamp_ns`
    ///   the value from `AImage_getTimestamp`.
    /// * `color`, when `Some`, **overrides** the AHB driver's suggested
    ///   `YCbCr` model on the compute-unpack path (see the field docs
    ///   above). It must be the stream's true matrix and range: a wrong
    ///   value is not unsound, but it silently decodes with the wrong
    ///   matrix, which is exactly the failure it exists to prevent.
    /// * No thread affinity for the handle itself; the usual acquire-fence
    ///   discipline still applies before reading the buffer's pixels.
    pub unsafe fn try_from_raw(
        image: *mut c_void,
        hardware: *mut c_void,
        timestamp_ns: i64,
        crop: Option<(i32, i32, i32, i32)>,
        format: PixelFormat,
        color: Option<video_types::ColorMetadata>,
        keep_alive: Option<KeepAlive>,
    ) -> Result<Self, InvalidHandleError> {
        if image.is_null() {
            return Err(InvalidHandleError::NullPointer("AImage"));
        }
        if hardware.is_null() {
            return Err(InvalidHandleError::NullPointer("AHardwareBuffer"));
        }
        Ok(Self { image, hardware, timestamp_ns, crop, format, color, keep_alive })
    }

    #[inline]
    pub fn image(&self) -> *mut c_void {
        self.image
    }
    #[inline]
    pub fn hardware(&self) -> *mut c_void {
        self.hardware
    }
    #[inline]
    pub fn timestamp_ns(&self) -> i64 {
        self.timestamp_ns
    }
    #[inline]
    pub fn crop(&self) -> Option<(i32, i32, i32, i32)> {
        self.crop
    }
    #[inline]
    pub fn format(&self) -> PixelFormat {
        self.format
    }
    /// Caller-known color metadata, when the producer signalled it. See the
    /// field docs — authoritative over the AHB driver's suggested YCbCr model
    /// on the compute-unpack path.
    #[inline]
    pub fn color(&self) -> Option<video_types::ColorMetadata> {
        self.color.clone()
    }
    #[inline]
    pub fn keep_alive(&self) -> Option<&KeepAlive> {
        self.keep_alive.as_ref()
    }
}

#[cfg(target_os = "android")]
impl fmt::Debug for AImageFrame {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("AImageFrame")
            .field("timestamp_ns", &self.timestamp_ns)
            .field("crop", &self.crop)
            .field("format", &self.format)
            .finish()
    }
}

#[cfg(target_os = "android")]
unsafe impl Send for AImageFrame {}
#[cfg(target_os = "android")]
unsafe impl Sync for AImageFrame {}

/// `ANativeWindow*` encoder input surface.
#[cfg(target_os = "android")]
#[derive(Clone)]
pub struct AndroidNativeWindowHandle {
    window: *mut c_void,
    keep_alive: Option<KeepAlive>,
}

#[cfg(target_os = "android")]
impl AndroidNativeWindowHandle {
    /// Wrap an `ANativeWindow*` encoder input surface. *Borrowing*: the
    /// handle is stored non-owningly, this type has no [`Drop`], and every
    /// obligation below extends to each [`Clone`].
    ///
    /// # Safety
    ///
    /// * `window` must point to a live `ANativeWindow` on which the
    ///   caller holds a reference — from `ANativeWindow_fromSurface`,
    ///   `AMediaCodec_createInputSurface`, or an equivalent. Null is
    ///   rejected as [`InvalidHandleError::NullPointer`] and is not a
    ///   caller obligation.
    /// * **Refcount:** no `ANativeWindow_acquire` is issued and there is
    ///   no `Drop` that would `ANativeWindow_release`. The caller's
    ///   reference must outlive this value and every [`Clone`] of it —
    ///   park it in `keep_alive`, or hold it directly when that is
    ///   `None`. Releasing while a clone survives is a use-after-free.
    /// * This is an **output-side** handle: the interop layer renders
    ///   into it and never treats it as an import source. The caller
    ///   must not concurrently dequeue or lock buffers from the same
    ///   window, since `ANativeWindow` has a single producer slot.
    /// * `AndroidNativeWindowHandle` is `Send + Sync`; the caller
    ///   asserts the window may be driven from the interop thread rather
    ///   than the one that created it.
    pub unsafe fn try_from_raw(window: *mut c_void, keep_alive: Option<KeepAlive>) -> Result<Self, InvalidHandleError> {
        if window.is_null() {
            return Err(InvalidHandleError::NullPointer("ANativeWindow"));
        }
        Ok(Self { window, keep_alive })
    }

    #[inline]
    pub fn window(&self) -> *mut c_void {
        self.window
    }
    #[inline]
    pub fn keep_alive(&self) -> Option<&KeepAlive> {
        self.keep_alive.as_ref()
    }
}

#[cfg(target_os = "android")]
impl fmt::Debug for AndroidNativeWindowHandle {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("AndroidNativeWindowHandle").finish_non_exhaustive()
    }
}

#[cfg(target_os = "android")]
unsafe impl Send for AndroidNativeWindowHandle {}
#[cfg(target_os = "android")]
unsafe impl Sync for AndroidNativeWindowHandle {}

/// `ASurfaceControl*` compositor layer (API 29+).
#[cfg(target_os = "android")]
#[derive(Clone)]
pub struct AndroidSurfaceControlHandle {
    surface_control: *mut c_void,
    keep_alive: Option<KeepAlive>,
}

#[cfg(target_os = "android")]
impl AndroidSurfaceControlHandle {
    /// Wrap an `ASurfaceControl*` compositor layer (API 29+). *Borrowing*:
    /// the handle is stored non-owningly, this type has no [`Drop`], and
    /// every obligation below extends to each [`Clone`].
    ///
    /// # Safety
    ///
    /// * `surface_control` must point to a live `ASurfaceControl`
    ///   created by `ASurfaceControl_create` /
    ///   `ASurfaceControl_createFromWindow` and not yet
    ///   `ASurfaceControl_release`d. Null is rejected as
    ///   [`InvalidHandleError::NullPointer`] and is not a caller
    ///   obligation.
    /// * **Refcount:** no `ASurfaceControl_acquire` is issued and there
    ///   is no `Drop` that releases. The caller's reference must outlive
    ///   this value and every [`Clone`] of it — park it in `keep_alive`,
    ///   or hold it directly when that is `None`.
    /// * Like [`AndroidNativeWindowHandle`], this is an **output-side**
    ///   handle: the interop layer submits transactions against it and
    ///   never imports from it.
    /// * `AndroidSurfaceControlHandle` is `Send + Sync`; the caller
    ///   asserts the layer may be driven from the interop thread.
    ///   `ASurfaceTransaction` batching is itself thread-safe, but the
    ///   caller must not interleave its own transactions on the same
    ///   layer in a way that reorders the interop layer's.
    pub unsafe fn try_from_raw(
        surface_control: *mut c_void,
        keep_alive: Option<KeepAlive>,
    ) -> Result<Self, InvalidHandleError> {
        if surface_control.is_null() {
            return Err(InvalidHandleError::NullPointer("ASurfaceControl"));
        }
        Ok(Self { surface_control, keep_alive })
    }

    #[inline]
    pub fn surface_control(&self) -> *mut c_void {
        self.surface_control
    }
    #[inline]
    pub fn keep_alive(&self) -> Option<&KeepAlive> {
        self.keep_alive.as_ref()
    }
}

#[cfg(target_os = "android")]
impl fmt::Debug for AndroidSurfaceControlHandle {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("AndroidSurfaceControlHandle").finish_non_exhaustive()
    }
}

#[cfg(target_os = "android")]
unsafe impl Send for AndroidSurfaceControlHandle {}
#[cfg(target_os = "android")]
unsafe impl Sync for AndroidSurfaceControlHandle {}

// ─────────────────────────────────────────────────────────────────────────────
// VAAPI (Linux)
// ─────────────────────────────────────────────────────────────────────────────

/// VAAPI surface (`VASurfaceID` + `VADisplay`), as a newtype so the
/// `GpuResource` enum carries it uniformly with the rest.
#[cfg(target_os = "linux")]
#[derive(Clone)]
pub struct VaapiSurface {
    surface: u32,
    display: *mut c_void,
    keep_alive: Option<KeepAlive>,
}

#[cfg(target_os = "linux")]
impl VaapiSurface {
    /// Wrap a `VASurfaceID` together with its `VADisplay`. *Borrowing*: the
    /// handle is stored non-owningly, this type has no [`Drop`], and every
    /// obligation below extends to each [`Clone`].
    ///
    /// # Safety
    ///
    /// * `display` must be a live `VADisplay` on which `vaInitialize`
    ///   succeeded and `vaTerminate` has not run. Null is rejected as
    ///   [`InvalidHandleError::NullPointer`] and is not a caller
    ///   obligation.
    /// * `surface` must be a `VASurfaceID` currently allocated on *that*
    ///   display. It is a plain `u32` index, so nothing distinguishes a
    ///   stale or fabricated id from a live one — including `0`, which
    ///   is deliberately **not** rejected here because `0` is a legal
    ///   `VASurfaceID`. Passing a destroyed surface makes the exporter's
    ///   `vaExportSurfaceHandle` address a recycled slot.
    /// * **Lifetime:** nothing is retained and there is no `Drop`.
    ///   Neither `vaDestroySurfaces` nor `vaTerminate` may run while
    ///   this value or any [`Clone`] of it is reachable, and the
    ///   surface must not be recycled back into the decoder's pool
    ///   either — a reused id silently yields another frame's pixels.
    ///   `keep_alive` exists to anchor the decoder context that owns
    ///   both; with `None` the caller carries the obligation.
    /// * **Thread affinity:** `VaapiSurface` is `Send + Sync`, but libva
    ///   serialises on a per-`VADisplay` lock and most drivers require
    ///   that a surface not be exported while the decoder is still
    ///   writing it. The caller must have completed
    ///   `vaSyncSurface` (or an equivalent fence) before handing the id
    ///   over.
    pub unsafe fn try_from_raw(
        surface: u32,
        display: *mut c_void,
        keep_alive: Option<KeepAlive>,
    ) -> Result<Self, InvalidHandleError> {
        if display.is_null() {
            return Err(InvalidHandleError::NullPointer("VADisplay"));
        }
        Ok(Self { surface, display, keep_alive })
    }

    #[inline]
    pub fn surface(&self) -> u32 {
        self.surface
    }
    #[inline]
    pub fn display(&self) -> *mut c_void {
        self.display
    }
    #[inline]
    pub fn keep_alive(&self) -> Option<&KeepAlive> {
        self.keep_alive.as_ref()
    }
}

#[cfg(target_os = "linux")]
impl fmt::Debug for VaapiSurface {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("VaapiSurface").field("surface", &self.surface).finish_non_exhaustive()
    }
}

#[cfg(target_os = "linux")]
unsafe impl Send for VaapiSurface {}
#[cfg(target_os = "linux")]
unsafe impl Sync for VaapiSurface {}

// ─────────────────────────────────────────────────────────────────────────────
// CPU
// ─────────────────────────────────────────────────────────────────────────────

/// Flat CPU byte buffer. The raw `ptr` is non-owning; `keep_alive` pins
/// whatever owns the backing allocation (an SDK decoder's frame anchor,
/// an aligned-buffer pool slot, a boxed expand buffer, …) so the bytes
/// outlive every clone the caller hands off. Pass `None` only when the
/// caller guarantees the allocation's lifetime by other means (e.g. a
/// test stack buffer that outlives the handle).
#[derive(Clone)]
pub struct CpuBytes {
    ptr: *mut u8,
    size: usize,
    row_pitch: u32,
    format: PixelFormat,
    keep_alive: Option<KeepAlive>,
}

impl CpuBytes {
    /// Wrap a flat CPU byte buffer. *Borrowing*: the handle is stored
    /// non-owningly, this type has no [`Drop`], and every obligation below
    /// extends to each [`Clone`].
    ///
    /// # Safety
    ///
    /// * `ptr` must point to `size` bytes that are valid to **read and
    ///   write** — upload paths read the whole range, readback paths
    ///   write it. Both `ptr == null` and `size == 0` are rejected
    ///   ([`InvalidHandleError::NullPointer`] /
    ///   [`InvalidHandleError::ZeroSize`]) and are therefore not caller
    ///   obligations; nothing else about the range is checkable here.
    /// * `row_pitch` must be the real row stride in bytes and `format`
    ///   the real layout, such that
    ///   `row_pitch * <rows implied by format and the consumer's extent>`
    ///   fits inside `size`. Consumers index rows by `row_pitch`, so an
    ///   over-stated pitch or format walks off the end of the
    ///   allocation.
    /// * **Aliasing.** The pointer is stored as `*mut u8` and handed to
    ///   consumers that may write through it, while [`Clone`] hands out
    ///   further copies. For the duration of this value and every clone
    ///   the caller must not hold a `&`/`&mut` Rust reference to the
    ///   same bytes, and must not let two consumers write the same range
    ///   concurrently — `CpuBytes` provides no synchronisation of its
    ///   own even though it is `Send + Sync`.
    /// * **Lifetime.** Nothing is retained and there is no `Drop`: the
    ///   backing allocation is neither freed nor kept alive here. It
    ///   must outlive this value and every clone, pinned either by the
    ///   `keep_alive` anchor (an SDK decoder's frame anchor, an
    ///   aligned-buffer pool slot, a boxed expand buffer) or, when
    ///   `keep_alive` is `None`, by the caller directly. A pool slot
    ///   recycled while a clone survives is a use-after-free.
    pub unsafe fn try_from_raw(
        ptr: *mut u8,
        size: usize,
        row_pitch: u32,
        format: PixelFormat,
        keep_alive: Option<KeepAlive>,
    ) -> Result<Self, InvalidHandleError> {
        if ptr.is_null() {
            return Err(InvalidHandleError::NullPointer("CPU bytes"));
        }
        if size == 0 {
            return Err(InvalidHandleError::ZeroSize("CPU bytes"));
        }
        Ok(Self { ptr, size, row_pitch, format, keep_alive })
    }

    #[inline]
    pub fn ptr(&self) -> *mut u8 {
        self.ptr
    }
    #[inline]
    pub fn size(&self) -> usize {
        self.size
    }
    #[inline]
    pub fn row_pitch(&self) -> u32 {
        self.row_pitch
    }
    #[inline]
    pub fn format(&self) -> PixelFormat {
        self.format
    }
    #[inline]
    pub fn keep_alive(&self) -> Option<&KeepAlive> {
        self.keep_alive.as_ref()
    }
}

impl fmt::Debug for CpuBytes {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("CpuBytes")
            .field("size", &self.size)
            .field("row_pitch", &self.row_pitch)
            .field("format", &self.format)
            .finish()
    }
}

// SAFETY: caller asserts thread-safe access to the byte range.
unsafe impl Send for CpuBytes {}
unsafe impl Sync for CpuBytes {}

/// Producer-allocated CPU staging slot. Caller cannot dereference; reads
/// land via the producer's readback API.
#[derive(Clone)]
pub struct CpuSharedSlot {
    size: u64,
    row_pitch: u32,
    format: PixelFormat,
    keep_alive: Option<KeepAlive>,
}

impl CpuSharedSlot {
    pub fn new(
        size: u64,
        row_pitch: u32,
        format: PixelFormat,
        keep_alive: Option<KeepAlive>,
    ) -> Result<Self, InvalidHandleError> {
        if size == 0 {
            return Err(InvalidHandleError::ZeroSize("CPU shared slot"));
        }
        Ok(Self { size, row_pitch, format, keep_alive })
    }

    #[inline]
    pub fn size(&self) -> u64 {
        self.size
    }
    #[inline]
    pub fn row_pitch(&self) -> u32 {
        self.row_pitch
    }
    #[inline]
    pub fn format(&self) -> PixelFormat {
        self.format
    }
    #[inline]
    pub fn keep_alive(&self) -> Option<&KeepAlive> {
        self.keep_alive.as_ref()
    }
}

impl fmt::Debug for CpuSharedSlot {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("CpuSharedSlot")
            .field("size", &self.size)
            .field("row_pitch", &self.row_pitch)
            .field("format", &self.format)
            .finish()
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Feature-gated typed-conversion methods
// ─────────────────────────────────────────────────────────────────────────────
//
// A conversion impl for a platform-only binding crate must be
// **double-gated** — both on the optional Cargo feature *and* on the
// matching `target_*` — so that `cargo check --all-features` on a
// non-target host stays green.
//
// ash compiles on every target (its handle types are `u64` newtypes), so
// the impls for `VkImage` / `VkBufferHandle` only need the feature gate.

#[cfg(feature = "ash")]
impl VkImage {
    /// Re-wrap the stored `u64` handle as ash's typed `vk::Image`.
    #[inline]
    pub fn as_ash_image(&self) -> ash::vk::Image {
        // `from_raw` is provided by the `ash::vk::Handle` trait; needs
        // a method-scope `use` so the trait is callable.
        use ash::vk::Handle;
        ash::vk::Image::from_raw(self.image)
    }
}

#[cfg(feature = "ash")]
impl VkBufferHandle {
    /// Re-wrap the stored `u64` handle as ash's typed `vk::Buffer`.
    #[inline]
    pub fn as_ash_buffer(&self) -> ash::vk::Buffer {
        use ash::vk::Handle;
        ash::vk::Buffer::from_raw(self.buffer)
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Unit tests
// ─────────────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod inline_tests {
    use super::*;

    // Test type used to verify keep-alive trait dispatch + Debug.
    #[derive(Debug)]
    struct _Marker;

    // `Arc<dyn ResourceKeepAlive>` is `Send + Sync` off wasm. On wasm the
    // `ResourceKeepAlive: MaybeSendSync` supertrait is the empty marker, so
    // the trait object is `!Send + !Sync` (the thread-affinity carve-out)
    // — assert the inverse there instead.
    #[cfg(not(target_family = "wasm"))]
    #[test]
    fn keep_alive_trait_object_send_sync() {
        fn assert_send_sync<T: Send + Sync>() {}
        assert_send_sync::<Arc<dyn ResourceKeepAlive>>();
    }

    #[cfg(target_family = "wasm")]
    static_assertions::assert_not_impl_any!(Arc<dyn ResourceKeepAlive>: Send, Sync);
}