quercus-core 0.7.0

Rust value types mirroring quercuscore (Rational, TimeRange, format enums) (internal; do not depend directly)
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
// Quercus Video Editor - Non-Linear Video Editor
// Copyright (C) 2026 Quercus Team
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

//! M5: importing platform hardware surfaces as wgpu textures.
//!
//! The video decoder produces hardware surfaces (VAAPI/NVDEC/D3D11VA/
//! VideoToolbox). Instead of downloading each frame to system memory and
//! re-uploading it, the surface's platform handle is wrapped into a
//! `wgpu::Texture` on the engine's own device:
//!
//! - **Linux**: the VAAPI surface's DMA-BUF plane (fd/offset/pitch/
//!   modifier) is imported into a raw Vulkan image
//!   (`VK_EXT_external_memory_dma_buf` + `VK_EXT_image_drm_format_modifier`)
//!   and wrapped through `wgpu_hal::vulkan::Device::texture_from_raw`.
//! - **Windows**: the D3D11VA texture's shared NT handle is wrapped via
//!   `wgpu_hal::vulkan::Device::texture_from_d3d11_shared_handle`.
//! - **macOS**: the VideoToolbox CVPixelBuffer's IOSurface is wrapped in a
//!   Metal texture (`newTextureWithDescriptor:iosurface:plane:`) and
//!   handed to `wgpu_hal::metal::Device::texture_from_raw`.
//!
//! Everything here is `unsafe` platform glue; the *only* consumer is the
//! decode import in `quercus-codec::gpuinterop`, and any failure must be
//! treated as "fall back to the staging path for this frame" — never as a
//! hard error that poisons later frames.

use std::sync::Arc;

#[cfg(target_os = "windows")]
use std::ffi::c_void;
#[cfg(target_os = "linux")]
use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
#[cfg(any(target_os = "linux", target_os = "windows"))]
use std::sync::OnceLock;

use super::*;

/// A DMA-BUF plane of a hardware frame (Linux/Vulkan import).
///
/// The `fd` is borrowed: the import duplicates it before handing it to
/// Vulkan, so the caller keeps ownership of the original.
#[cfg(target_os = "linux")]
#[derive(Clone, Copy, Debug)]
pub struct DmaBufPlane {
	/// DMA-BUF file descriptor.
	pub fd: i32,
	/// Byte offset of the plane inside the buffer object.
	pub offset: u64,
	/// Row pitch in bytes.
	pub pitch: u64,
	/// DRM format modifier (`DRM_FORMAT_MOD_*`).
	pub modifier: u64,
}

/// Platform external memory backing one wgpu texture (OpenFX GL
/// zero-copy): a Linux `OPAQUE_FD` or a Windows `OPAQUE_WIN32` NT handle.
///
/// The texture itself owns the `VkImage`/`VkDeviceMemory` through the
/// wgpu-hal drop callback. This struct only keeps the exported handle
/// (closed on drop) and the metadata GL needs for the matching
/// `glImportMemory*` / `glTexStorageMem2DEXT` call.
#[cfg(any(target_os = "linux", target_os = "windows"))]
pub(crate) struct ExternalTexture {
	#[cfg(target_os = "linux")]
	fd: OwnedFd,
	#[cfg(target_os = "windows")]
	handle: isize,
	size: u64,
	width: u32,
	height: u32,
	format: wgpu::TextureFormat,
}

#[cfg(target_os = "windows")]
impl Drop for ExternalTexture {
	fn drop(&mut self) {
		unsafe {
			CloseHandle(self.handle as *mut c_void);
		}
	}
}

/// A borrowed handle to a wgpu texture whose Vulkan memory is exportable
/// (Linux `OPAQUE_FD` / Windows `OPAQUE_WIN32`).
///
/// It keeps the wgpu texture alive and exposes a duplicate handle. The
/// caller imports the duplicate into GL; GL takes ownership of that
/// duplicate and closes it when the memory object is deleted.
#[cfg(any(target_os = "linux", target_os = "windows"))]
#[derive(Clone)]
pub struct GlMemoryExport {
	external: Arc<ExternalTexture>,
	/// Keeps the wgpu/hal texture (and its drop callback) alive while the
	/// plugin renders into the imported GL texture.
	_texture: Arc<wgpu::Texture>,
}

#[cfg(any(target_os = "linux", target_os = "windows"))]
impl GlMemoryExport {
	/// Width in pixels of the exported texture.
	///
	/// This is the extent the GL memory object is created with (via the
	/// `glImportMemory*` call), so it must match the image the plugin renders
	/// into.
	pub fn width(&self) -> u32 {
		self.external.width
	}
	/// Height in pixels of the exported texture.
	///
	/// This is the extent the GL memory object is created with (via the
	/// `glImportMemory*` call), so it must match the image the plugin renders
	/// into.
	pub fn height(&self) -> u32 {
		self.external.height
	}
	/// The `wgpu::TextureFormat` of the exported texture.
	///
	/// The GL bridge maps it to the matching internal format when creating the
	/// imported GL texture; it is the format requested at creation.
	pub fn format(&self) -> wgpu::TextureFormat {
		self.external.format
	}
	/// Allocation size in bytes (the `size` argument of
	/// `glImportMemoryFdEXT` / `glImportMemoryWin32HandleEXT`).
	pub fn size(&self) -> u64 {
		self.external.size
	}

	/// Linux: duplicate the exported opaque fd. The caller owns the
	/// returned fd and must hand it to exactly one GL memory object (or
	/// close it).
	#[cfg(target_os = "linux")]
	pub fn try_clone_fd(&self) -> Result<OwnedFd> {
		let fd = unsafe { libc::dup(self.external.fd.as_raw_fd()) };
		if fd < 0 {
			return Err(Error::Failed("dup(opaque fd) failed".into()));
		}
		Ok(unsafe { OwnedFd::from_raw_fd(fd) })
	}

	/// Windows: duplicate the exported NT handle. The caller owns the
	/// duplicate and must hand it to exactly one GL memory object (or
	/// close it).
	#[cfg(target_os = "windows")]
	pub fn try_clone_handle(&self) -> Result<isize> {
		let mut duplicate = 0isize;
		let ok = unsafe {
			DuplicateHandle(
				GetCurrentProcess(),
				self.external.handle,
				GetCurrentProcess(),
				&mut duplicate,
				0,
				0,
				DUPLICATE_SAME_ACCESS,
			)
		};
		if ok == 0 {
			return Err(Error::Failed("DuplicateHandle(opaque win32) failed".into()));
		}
		Ok(duplicate)
	}
}

#[cfg(target_os = "windows")]
const DUPLICATE_SAME_ACCESS: u32 = 0x0000_0002;

#[cfg(target_os = "windows")]
#[link(name = "kernel32")]
unsafe extern "system" {
	fn GetCurrentProcess() -> *mut c_void;
	fn DuplicateHandle(
		h_source_process: *mut c_void,
		h_source_handle: isize,
		h_target_process: *mut c_void,
		lp_target_handle: *mut isize,
		dw_desired_access: u32,
		b_inherit_handle: i32,
		dw_options: u32,
	) -> i32;
	fn CloseHandle(h_object: *mut c_void) -> i32;
}

#[cfg(any(target_os = "linux", target_os = "windows"))]
struct AshDispatch {
	_entry: ash::Entry,
	_instance: ash::Instance,
	get_device_proc_addr: ash::vk::PFN_vkGetDeviceProcAddr,
}

#[cfg(any(target_os = "linux", target_os = "windows"))]
impl AshDispatch {
	#[cfg(target_os = "linux")]
	fn get_memory_fd(&self, device: ash::vk::Device) -> Option<ash::vk::PFN_vkGetMemoryFdKHR> {
		let name = std::ffi::CStr::from_bytes_with_nul(b"vkGetMemoryFdKHR\0").ok()?;
		let raw = unsafe { (self.get_device_proc_addr)(device, name.as_ptr()) }?;
		Some(unsafe { std::mem::transmute(raw) })
	}

	#[cfg(target_os = "windows")]
	fn get_memory_win32_handle(
		&self,
		device: ash::vk::Device,
	) -> Option<ash::vk::PFN_vkGetMemoryWin32HandleKHR> {
		let name = std::ffi::CStr::from_bytes_with_nul(b"vkGetMemoryWin32HandleKHR\0").ok()?;
		let raw = unsafe { (self.get_device_proc_addr)(device, name.as_ptr()) }?;
		Some(unsafe { std::mem::transmute(raw) })
	}
}

// SAFETY: the dispatch table is immutable after construction; Vulkan
// function pointers and the instance handle are process-level, and the
// context method calling this is already Send+Sync.
#[cfg(any(target_os = "linux", target_os = "windows"))]
unsafe impl Send for AshDispatch {}
#[cfg(any(target_os = "linux", target_os = "windows"))]
unsafe impl Sync for AshDispatch {}

#[cfg(any(target_os = "linux", target_os = "windows"))]
/// Lazily creates the process-wide Vulkan instance used for external-memory
/// handle queries.
///
/// The instance is created once (guarded by a `OnceLock`) with API version 1.1
/// and kept for the process lifetime; later calls return the same dispatch
/// table. Returns `None` when the Vulkan loader cannot be loaded or instance
/// creation fails, in which case callers import the memory without the
/// handle-extension query and fail cleanly instead of panicking.
fn ash_dispatch() -> Option<&'static AshDispatch> {
	static DISPATCH: OnceLock<Option<AshDispatch>> = OnceLock::new();
	DISPATCH
		.get_or_init(|| unsafe {
			let entry = ash::Entry::load().ok()?;
			let app = ash::vk::ApplicationInfo::default().api_version(ash::vk::API_VERSION_1_1);
			let create = ash::vk::InstanceCreateInfo::default().application_info(&app);
			let instance = entry.create_instance(&create, None).ok()?;
			let get_device_proc_addr = instance.fp_v1_0().get_device_proc_addr;
			Some(AshDispatch {
				_entry: entry,
				_instance: instance,
				get_device_proc_addr,
			})
		})
		.as_ref()
}

/// The Metal pixel format for an IOSurface plane (macOS)./// The Metal pixel format for an IOSurface plane (macOS).
#[cfg(target_os = "macos")]
fn iosurface_pixel_format(format: wgpu::TextureFormat) -> Option<objc2_metal::MTLPixelFormat> {
	use objc2_metal::MTLPixelFormat;
	Some(match format {
		wgpu::TextureFormat::R8Unorm => MTLPixelFormat::R8Unorm,
		wgpu::TextureFormat::Rg8Unorm => MTLPixelFormat::RG8Unorm,
		wgpu::TextureFormat::R16Unorm => MTLPixelFormat::R16Unorm,
		wgpu::TextureFormat::Rg16Unorm => MTLPixelFormat::RG16Unorm,
		_ => return None,
	})
}

/// Registration parameters for one imported texture alias: dimensions,
/// array size, layout, plane aspect and the selected array slice (M5).
#[derive(Clone, Copy)]
struct ImportedTextureDesc {
	width: u32,
	height: u32,
	array_layers: u32,
	format: wgpu::TextureFormat,
	aspect: wgpu::TextureAspect,
	layer: Option<(u32, u32)>,
}

/// Caller-owned resource tied to an imported texture's lifetime (M5):
/// the decoder's hardware `AVFrame` stays alive until the GPU texture is
/// destroyed, so the decoder's surface pool cannot recycle the memory
/// while the GPU still samples it. The closure runs exactly once, right
/// before the platform resources are released.
pub type ImportGuard = Box<dyn FnOnce() + Send + Sync>;

/// The plane formats the import accepts. Kept small on purpose: luma and
/// interleaved chroma for 8-bit NV12 and 16-bit-container P010.
#[cfg(target_os = "linux")]
fn import_vk_format(format: wgpu::TextureFormat) -> Option<ash::vk::Format> {
	use ash::vk::Format;
	Some(match format {
		wgpu::TextureFormat::R8Unorm => Format::R8_UNORM,
		wgpu::TextureFormat::Rg8Unorm => Format::R8G8_UNORM,
		wgpu::TextureFormat::R16Unorm => Format::R16_UNORM,
		wgpu::TextureFormat::Rg16Unorm => Format::R16G16_UNORM,
		_ => return None,
	})
}

impl GpuContext {
	/// Import one DMA-BUF plane as a GPU texture (Linux/Vulkan).
	///
	/// Returns the registry token. `keep_alive` (the decoder's mapped
	/// `AVFrame`) runs when the GPU texture is destroyed, after the GPU is
	/// done with it.
	#[cfg(target_os = "linux")]
	pub fn import_dmabuf_plane(
		&self,
		width: u32,
		height: u32,
		format: wgpu::TextureFormat,
		plane: DmaBufPlane,
		keep_alive: Option<ImportGuard>,
	) -> Result<u64> {
		use ash::vk;
		use wgpu::hal;

		if self.kind != BackendKind::Vulkan || width == 0 || height == 0 {
			return Err(Error::State);
		}
		let Some(vk_format) = import_vk_format(format) else {
			return Err(Error::Invalid);
		};
		let guard = unsafe { self.device.as_hal::<hal::api::Vulkan>() }.ok_or(Error::State)?;
		let hal_device: &hal::vulkan::Device = &guard;
		let raw = hal_device.raw_device().clone();
		let _ = hal_device.raw_physical_device();

		let layouts = [vk::SubresourceLayout {
			offset: plane.offset,
			size: 0,
			row_pitch: plane.pitch,
			array_pitch: 0,
			depth_pitch: 0,
		}];
		let external = vk::ExternalMemoryImageCreateInfo::default()
			.handle_types(vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT);
		let mut modifier = vk::ImageDrmFormatModifierExplicitCreateInfoEXT::default()
			.drm_format_modifier(plane.modifier)
			.plane_layouts(&layouts);
		modifier.p_next = (&external as *const vk::ExternalMemoryImageCreateInfo).cast();

		let info = vk::ImageCreateInfo::default()
			.image_type(vk::ImageType::TYPE_2D)
			.format(vk_format)
			.extent(vk::Extent3D {
				width,
				height,
				depth: 1,
			})
			.mip_levels(1)
			.array_layers(1)
			.samples(vk::SampleCountFlags::TYPE_1)
			.tiling(vk::ImageTiling::DRM_FORMAT_MODIFIER_EXT)
			.usage(vk::ImageUsageFlags::SAMPLED)
			.sharing_mode(vk::SharingMode::EXCLUSIVE)
			.initial_layout(vk::ImageLayout::UNDEFINED)
			.push_next(&mut modifier);
		let image = unsafe { raw.create_image(&info, None) }
			.map_err(|e| Error::Failed(format!("vkCreateImage(dmabuf): {e:?}")))?;

		let req = unsafe { raw.get_image_memory_requirements(image) };

		// Duplicate the fd: Vulkan takes ownership of the imported fd on a
		// successful `vkAllocateMemory` and closes it when the memory is
		// freed; the decoder keeps its own.
		let dup_fd = unsafe { libc::dup(plane.fd) };
		if dup_fd < 0 {
			unsafe { raw.destroy_image(image, None) };
			return Err(Error::Failed("dup(dmabuf fd) failed".into()));
		}
		// Pick the memory type by trying the compatible ones in order —
		// `vkGetPhysicalDeviceMemoryProperties` is instance-level and
		// wgpu-hal keeps its raw instance private. The compatible set is
		// usually tiny (often one DEVICE_LOCAL type on discrete GPUs).
		let mut import = vk::ImportMemoryFdInfoKHR::default()
			.handle_type(vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT)
			.fd(dup_fd);
		let mut dedicated = vk::MemoryDedicatedAllocateInfo::default().image(image);
		let mut last_err = None;
		let mut memory = None;
		for type_index in 0..32u32 {
			if req.memory_type_bits & (1 << type_index) == 0 {
				continue;
			}
			let alloc = vk::MemoryAllocateInfo::default()
				.allocation_size(req.size)
				.memory_type_index(type_index)
				.push_next(&mut dedicated)
				.push_next(&mut import);
			match unsafe { raw.allocate_memory(&alloc, None) } {
				Ok(m) => {
					memory = Some(m);
					break;
				}
				Err(e) => last_err = Some((type_index, e)),
			}
		}
		let Some(memory) = memory else {
			unsafe {
				libc::close(dup_fd);
				raw.destroy_image(image, None);
			}
			return Err(Error::Failed(format!(
				"vkAllocateMemory(import) failed for every compatible type: {last_err:?}"
			)));
		};
		if let Err(e) = unsafe { raw.bind_image_memory(image, memory, 0) } {
			unsafe {
				raw.free_memory(memory, None);
				raw.destroy_image(image, None);
			}
			return Err(Error::Failed(format!("vkBindImageMemory: {e:?}")));
		}

		let hal_desc = hal::TextureDescriptor {
			label: Some("quercusrender-imported-dmabuf"),
			size: wgpu::Extent3d {
				width,
				height,
				depth_or_array_layers: 1,
			},
			mip_level_count: 1,
			sample_count: 1,
			dimension: wgpu::TextureDimension::D2,
			format,
			usage: wgpu_types::TextureUses::RESOURCE,
			memory_flags: hal::MemoryFlags::empty(),
			view_formats: Vec::new(),
		};
		// wgpu-hal does not destroy external images (it cannot know how);
		// the drop guard owns both the image and the imported memory, and
		// carries the decoder's frame-keep-alive with it.
		let raw_guard = raw.clone();
		let drop_guard: hal::DropCallback = Box::new(move || unsafe {
			if let Some(keep) = keep_alive {
				keep();
			}
			raw_guard.destroy_image(image, None);
			raw_guard.free_memory(memory, None);
		});
		let hal_texture = unsafe {
			hal_device.texture_from_raw(
				image,
				&hal_desc,
				Some(drop_guard),
				hal::vulkan::TextureMemory::External,
			)
		};
		self.register_imported_texture::<hal::api::Vulkan>(
			hal_texture,
			ImportedTextureDesc {
				width,
				height,
				array_layers: 1,
				format,
				aspect: wgpu::TextureAspect::All,
				layer: None,
			},
		)
	}

	/// Import one plane of an opaque Linux FD (CUDA VMM / driver-private
	/// handle) as a linear Vulkan image.
	///
	/// The FD is duplicated and owned by Vulkan after a successful allocation;
	/// the image is registered like the DMA-BUF path and addressed by the linear
	/// image extents.
	///
	/// # Arguments
	///
	/// * `width` / `height` - plane size in pixels; must be non-zero.
	/// * `format` - plane format; 16-bit normalized formats additionally require
	///   the device's 16-bit-normalized feature.
	/// * `fd` - opaque Linux file descriptor; duplicated internally, so the
	///   caller keeps ownership of `fd`.
	/// * `offset` - byte offset into the exported allocation.
	/// * `_pitch` - retained for layout diagnostics only; linear image addressing
	///   is driven by the image extents.
	/// * `keep_alive` - optional guard dropped when the imported texture is
	///   released, keeping the producer's memory alive while GL reads it.
	///
	/// # Errors
	///
	/// `Error::State` for a non-Vulkan context, a zero size, or a 16-bit
	/// normalized format the device does not support; `Error::Invalid` for a
	/// format with no Vulkan equivalent; `Error::Failed` when the fd duplication
	/// or image/memory creation fails.
	#[cfg(target_os = "linux")]
	pub fn import_opaque_fd_plane(
		&self,
		width: u32,
		height: u32,
		format: wgpu::TextureFormat,
		fd: i32,
		offset: u64,
		_pitch: u64,
		keep_alive: Option<ImportGuard>,
	) -> Result<u64> {
		use ash::vk;
		use wgpu::hal;

		if self.kind != BackendKind::Vulkan || width == 0 || height == 0 {
			return Err(Error::State);
		}
		// A host-adopted device may not have enabled the 16-bit normalized
		// texture feature. Creating such an external texture anyway produces
		// an invalid bind group at draw time; report a capability gap so the
		// decoder falls back to staging instead.
		if matches!(
			format,
			wgpu::TextureFormat::R16Unorm
				| wgpu::TextureFormat::Rg16Unorm
				| wgpu::TextureFormat::Rgba16Unorm
		) && !self.supports_16bit_norm_planes()
		{
			return Err(Error::State);
		}
		let Some(vk_format) = import_vk_format(format) else {
			return Err(Error::Invalid);
		};
		let guard = unsafe { self.device.as_hal::<hal::api::Vulkan>() }.ok_or(Error::State)?;
		let hal_device: &hal::vulkan::Device = &guard;
		let raw = hal_device.raw_device().clone();
		let _ = hal_device.raw_physical_device();

		let mut external = vk::ExternalMemoryImageCreateInfo::default()
			.handle_types(vk::ExternalMemoryHandleTypeFlags::OPAQUE_FD);
		let info = vk::ImageCreateInfo::default()
			.image_type(vk::ImageType::TYPE_2D)
			.format(vk_format)
			.extent(vk::Extent3D {
				width,
				height,
				depth: 1,
			})
			.mip_levels(1)
			.array_layers(1)
			.samples(vk::SampleCountFlags::TYPE_1)
			.tiling(vk::ImageTiling::LINEAR)
			.usage(vk::ImageUsageFlags::SAMPLED)
			.sharing_mode(vk::SharingMode::EXCLUSIVE)
			.initial_layout(vk::ImageLayout::UNDEFINED)
			.push_next(&mut external);
		let image = unsafe { raw.create_image(&info, None) }
			.map_err(|e| Error::Failed(format!("vkCreateImage(dmabuf): {e:?}")))?;

		let req = unsafe { raw.get_image_memory_requirements(image) };

		// Duplicate the fd: Vulkan takes ownership of the imported fd on a
		// successful `vkAllocateMemory` and closes it when the memory is
		// freed; the decoder keeps its own.
		let dup_fd = unsafe { libc::dup(fd) };
		if dup_fd < 0 {
			unsafe { raw.destroy_image(image, None) };
			return Err(Error::Failed("dup(dmabuf fd) failed".into()));
		}
		// Pick the memory type by trying the compatible ones in order —
		// `vkGetPhysicalDeviceMemoryProperties` is instance-level and
		// wgpu-hal keeps its raw instance private. The compatible set is
		// usually tiny (often one DEVICE_LOCAL type on discrete GPUs).
		let mut import = vk::ImportMemoryFdInfoKHR::default()
			.handle_type(vk::ExternalMemoryHandleTypeFlags::OPAQUE_FD)
			.fd(dup_fd);
		let mut dedicated = vk::MemoryDedicatedAllocateInfo::default().image(image);
		let mut last_err = None;
		let mut memory = None;
		for type_index in 0..32u32 {
			if req.memory_type_bits & (1 << type_index) == 0 {
				continue;
			}
			let alloc = vk::MemoryAllocateInfo::default()
				.allocation_size(req.size)
				.memory_type_index(type_index)
				.push_next(&mut dedicated)
				.push_next(&mut import);
			match unsafe { raw.allocate_memory(&alloc, None) } {
				Ok(m) => {
					memory = Some(m);
					break;
				}
				Err(e) => last_err = Some((type_index, e)),
			}
		}
		let Some(memory) = memory else {
			unsafe {
				libc::close(dup_fd);
				raw.destroy_image(image, None);
			}
			return Err(Error::Failed(format!(
				"vkAllocateMemory(import) failed for every compatible type: {last_err:?}"
			)));
		};
		if let Err(e) = unsafe { raw.bind_image_memory(image, memory, offset) } {
			unsafe {
				raw.free_memory(memory, None);
				raw.destroy_image(image, None);
			}
			return Err(Error::Failed(format!("vkBindImageMemory: {e:?}")));
		}

		let hal_desc = hal::TextureDescriptor {
			label: Some("quercusrender-imported-dmabuf"),
			size: wgpu::Extent3d {
				width,
				height,
				depth_or_array_layers: 1,
			},
			mip_level_count: 1,
			sample_count: 1,
			dimension: wgpu::TextureDimension::D2,
			format,
			usage: wgpu_types::TextureUses::RESOURCE,
			memory_flags: hal::MemoryFlags::empty(),
			view_formats: Vec::new(),
		};
		// wgpu-hal does not destroy external images (it cannot know how);
		// the drop guard owns both the image and the imported memory, and
		// carries the decoder's frame-keep-alive with it.
		let raw_guard = raw.clone();
		let drop_guard: hal::DropCallback = Box::new(move || unsafe {
			if let Some(keep) = keep_alive {
				keep();
			}
			raw_guard.destroy_image(image, None);
			raw_guard.free_memory(memory, None);
		});
		let hal_texture = unsafe {
			hal_device.texture_from_raw(
				image,
				&hal_desc,
				Some(drop_guard),
				hal::vulkan::TextureMemory::External,
			)
		};
		self.register_imported_texture::<hal::api::Vulkan>(
			hal_texture,
			ImportedTextureDesc {
				width,
				height,
				array_layers: 1,
				format,
				aspect: wgpu::TextureAspect::All,
				layer: None,
			},
		)
	}

	/// Import one slice of a D3D11VA texture array shared as an NT handle
	/// (Windows/Vulkan): one multi-planar image (`NV12`/`P010`) with
	/// `array_size` layers, registered twice (planes 0/1) for `slice`.
	///
	/// D3D11VA frames cycle through the decoder's surface array
	/// (`AVFrame::data[1]` is the slice index), so the imported VkImage
	/// must carry the whole array and the tokens must select their slice —
	/// otherwise only every N-th frame would be importable (M5 audit).
	///
	/// `keep_alive` runs when the image is destroyed; the handle itself is
	/// owned by the caller (Vulkan takes a resource reference, not the
	/// handle).
	#[cfg(target_os = "windows")]
	pub fn import_d3d11_shared_texture(
		&self,
		shared_handle: isize,
		width: u32,
		height: u32,
		format: wgpu::TextureFormat,
		array_size: u32,
		slice: u32,
		keep_alive: Option<ImportGuard>,
	) -> Result<(u64, u64)> {
		use ash::vk;
		use wgpu::hal;

		if self.kind != BackendKind::Vulkan || width == 0 || height == 0 {
			return Err(Error::State);
		}
		let array_size = array_size.max(1);
		if slice >= array_size {
			return Err(Error::Invalid);
		}
		let (vk_format, required_feature) = match format {
			wgpu::TextureFormat::NV12 => (
				vk::Format::G8_B8R8_2PLANE_420_UNORM,
				wgpu::Features::TEXTURE_FORMAT_NV12,
			),
			wgpu::TextureFormat::P010 => (
				vk::Format::G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16,
				wgpu::Features::TEXTURE_FORMAT_P010,
			),
			_ => return Err(Error::Invalid),
		};
		// Multi-planar formats need their device feature; without it the
		// hal texture would be created but every view invalid.
		if !self.device.features().contains(required_feature) {
			return Err(Error::State);
		}
		let guard = unsafe { self.device.as_hal::<hal::api::Vulkan>() }.ok_or(Error::State)?;
		let hal_device: &hal::vulkan::Device = &guard;
		let raw = hal_device.raw_device().clone();

		let mut external = vk::ExternalMemoryImageCreateInfo::default()
			.handle_types(vk::ExternalMemoryHandleTypeFlags::D3D11_TEXTURE);
		let info = vk::ImageCreateInfo::default()
			.image_type(vk::ImageType::TYPE_2D)
			.format(vk_format)
			.extent(vk::Extent3D {
				width,
				height,
				depth: 1,
			})
			.mip_levels(1)
			.array_layers(array_size)
			.samples(vk::SampleCountFlags::TYPE_1)
			.tiling(vk::ImageTiling::OPTIMAL)
			.usage(vk::ImageUsageFlags::SAMPLED)
			.sharing_mode(vk::SharingMode::EXCLUSIVE)
			.initial_layout(vk::ImageLayout::UNDEFINED)
			.push_next(&mut external);
		let image = unsafe { raw.create_image(&info, None) }
			.map_err(|e| Error::Failed(format!("vkCreateImage(d3d11): {e:?}")))?;

		let req = unsafe { raw.get_image_memory_requirements(image) };
		// Dedicated allocation is required for imported D3D11 textures.
		let mut import = vk::ImportMemoryWin32HandleInfoKHR::default()
			.handle_type(vk::ExternalMemoryHandleTypeFlags::D3D11_TEXTURE)
			.handle(shared_handle);
		let mut dedicated = vk::MemoryDedicatedAllocateInfo::default().image(image);
		let mut last_err = None;
		let mut memory = None;
		for type_index in 0..32u32 {
			if req.memory_type_bits & (1 << type_index) == 0 {
				continue;
			}
			let alloc = vk::MemoryAllocateInfo::default()
				.allocation_size(req.size)
				.memory_type_index(type_index)
				.push_next(&mut dedicated)
				.push_next(&mut import);
			match unsafe { raw.allocate_memory(&alloc, None) } {
				Ok(m) => {
					memory = Some(m);
					break;
				}
				Err(e) => last_err = Some((type_index, e)),
			}
		}
		let Some(memory) = memory else {
			unsafe { raw.destroy_image(image, None) };
			return Err(Error::Failed(format!(
				"vkAllocateMemory(import d3d11) failed: {last_err:?}"
			)));
		};
		if let Err(e) = unsafe { raw.bind_image_memory(image, memory, 0) } {
			unsafe {
				raw.free_memory(memory, None);
				raw.destroy_image(image, None);
			}
			return Err(Error::Failed(format!("vkBindImageMemory: {e:?}")));
		}

		let hal_desc = hal::TextureDescriptor {
			label: Some("quercusrender-imported-d3d11"),
			size: wgpu::Extent3d {
				width,
				height,
				depth_or_array_layers: array_size,
			},
			mip_level_count: 1,
			sample_count: 1,
			dimension: wgpu::TextureDimension::D2,
			format,
			usage: wgpu_types::TextureUses::RESOURCE,
			memory_flags: hal::MemoryFlags::empty(),
			view_formats: Vec::new(),
		};
		let raw_guard = raw.clone();
		let drop_guard: hal::DropCallback = Box::new(move || unsafe {
			if let Some(keep) = keep_alive {
				keep();
			}
			raw_guard.destroy_image(image, None);
			raw_guard.free_memory(memory, None);
		});
		let hal_texture = unsafe {
			hal_device.texture_from_raw(
				image,
				&hal_desc,
				Some(drop_guard),
				hal::vulkan::TextureMemory::External,
			)
		};
		// Two plane views of the chosen slice of the multi-planar array:
		// Y at plane 0, interleaved chroma at plane 1.
		let desc = ImportedTextureDesc {
			width,
			height,
			array_layers: array_size,
			format,
			aspect: wgpu::TextureAspect::Plane0,
			layer: Some((slice, 1)),
		};
		let (y, texture) =
			self.register_imported_texture_shared::<hal::api::Vulkan>(hal_texture, desc)?;
		let uv = self.register_texture_entry(
			texture,
			ImportedTextureDesc {
				// The chroma plane's view is half-size; the planar pass
				// derives the sampling scale from the registered sizes.
				width: width.div_ceil(2),
				height: height.div_ceil(2),
				aspect: wgpu::TextureAspect::Plane1,
				..desc
			},
		);
		Ok((y, uv))
	}

	/// Import one IOSurface plane as a Metal-backed texture (macOS): the
	/// VideoToolbox pixel buffer's surface stays owned by the decoder; the
	/// caller keeps it alive via the planar texture's guard.
	///
	/// # Safety
	///
	/// `iosurface` must be a live `IOSurfaceRef` that stays valid until
	/// the imported texture is destroyed (the decoder's frame reference is
	/// held by the planar texture's keep-alive guard).
	#[cfg(target_os = "macos")]
	pub unsafe fn import_iosurface_plane(
		&self,
		iosurface: *mut std::ffi::c_void,
		plane: u32,
		width: u32,
		height: u32,
		format: wgpu::TextureFormat,
	) -> Result<u64> {
		use objc2::rc::Retained;
		use objc2::runtime::ProtocolObject;
		use objc2_io_surface::IOSurfaceRef;
		use objc2_metal::{
			MTLDevice as _, MTLStorageMode, MTLTextureDescriptor, MTLTextureType, MTLTextureUsage,
		};
		use wgpu::hal;

		if self.kind != BackendKind::Metal || width == 0 || height == 0 || iosurface.is_null() {
			return Err(Error::State);
		}
		let Some(pixel_format) = iosurface_pixel_format(format) else {
			return Err(Error::Invalid);
		};
		let guard = unsafe { self.device.as_hal::<hal::api::Metal>() }.ok_or(Error::State)?;
		let hal_device: &hal::metal::Device = &guard;
		let device: &Retained<ProtocolObject<dyn objc2_metal::MTLDevice>> = hal_device.raw_device();

		let descriptor = MTLTextureDescriptor::new();
		descriptor.setTextureType(MTLTextureType::Type2D);
		descriptor.setPixelFormat(pixel_format);
		descriptor.setStorageMode(MTLStorageMode::Shared);
		descriptor.setUsage(MTLTextureUsage::ShaderRead);
		// SAFETY: plain descriptor field setters.
		unsafe {
			descriptor.setWidth(width as usize);
			descriptor.setHeight(height as usize);
			descriptor.setMipmapLevelCount(1);
		}
		// SAFETY: the caller guarantees a live IOSurface for the texture's
		// lifetime (the planar texture holds its keep-alive guard).
		let surface: &IOSurfaceRef = unsafe { &*(iosurface as *const IOSurfaceRef) };
		// SAFETY: `surface` is a live IOSurface for the texture's lifetime
		// (the caller's planar keep-alive holds the pixel buffer).
		let texture = device
			.newTextureWithDescriptor_iosurface_plane(&descriptor, surface, plane as usize)
			.ok_or_else(|| {
				Error::Failed("newTextureWithDescriptor:iosurface: returned nil".into())
			})?;

		let raw_type = MTLTextureType::Type2D;
		let hal_texture = unsafe {
			hal::metal::Device::texture_from_raw(
				texture,
				format,
				raw_type,
				1,
				1,
				hal::CopyExtent {
					width,
					height,
					depth: 1,
				},
			)
		};
		self.register_imported_texture::<hal::api::Metal>(
			hal_texture,
			ImportedTextureDesc {
				width,
				height,
				array_layers: 1,
				format,
				aspect: wgpu::TextureAspect::All,
				layer: None,
			},
		)
	}

	/// Registers a texture created through `create_texture_from_hal` and returns
	/// its registry token.
	///
	/// Shared tail of every platform import path (Linux dma-buf/opaque FD,
	/// Windows OPAQUE_WIN32, macOS IOSurface); the token is what later calls such
	/// as `texture_view` use to find the texture.
	///
	/// # Arguments
	///
	/// * `hal_texture` - hal texture produced by the platform importer.
	/// * `desc` - size/format/aspect/layer metadata for the registry entry.
	fn register_imported_texture<A: wgpu::hal::Api>(
		&self,
		hal_texture: A::Texture,
		desc: ImportedTextureDesc,
	) -> Result<u64> {
		self.register_imported_texture_shared::<A>(hal_texture, desc)
			.map(|(token, _)| token)
	}

	/// Creates the wgpu texture from `hal_texture`, registers it, and returns
	/// `(token, texture)`.
	///
	/// The returned `Arc` lets multi-plane/array importers register aliases for a
	/// single GPU texture (different plane aspects or layer ranges) without
	/// recreating it. Marks the context as used.
	///
	/// # Arguments
	///
	/// * `hal_texture` - hal texture produced by the platform importer.
	/// * `desc` - size/format/aspect/layer metadata for the registry entry.
	///
	/// The `Result` is part of the shared call shape used by every platform
	/// importer; this implementation currently never returns `Err`.
	fn register_imported_texture_shared<A: wgpu::hal::Api>(
		&self,
		hal_texture: A::Texture,
		desc: ImportedTextureDesc,
	) -> Result<(u64, Arc<wgpu::Texture>)> {
		let texture_desc = wgpu::TextureDescriptor {
			label: Some("quercusrender-imported"),
			size: wgpu::Extent3d {
				width: desc.width,
				height: desc.height,
				depth_or_array_layers: desc.array_layers.max(1),
			},
			mip_level_count: 1,
			sample_count: 1,
			dimension: wgpu::TextureDimension::D2,
			format: desc.format,
			usage: wgpu::TextureUsages::TEXTURE_BINDING,
			view_formats: &[],
		};
		let texture = unsafe {
			self.device
				.create_texture_from_hal::<A>(hal_texture, &texture_desc)
		};
		self.used.store(true, Ordering::Release);
		let texture = Arc::new(texture);
		let token = self.register_texture_entry(texture.clone(), desc);
		Ok((token, texture))
	}

	/// Inserts one registry entry for `texture` and returns its new token.
	///
	/// The token is a monotonically increasing `u64` (relaxed atomic) and is the
	/// handle later texture-API calls use to look the texture up. The entry takes
	/// one `Arc<wgpu::Texture>` reference and stores the caller-reported
	/// dimensions, format, aspect and array-layer range.
	///
	/// # Arguments
	///
	/// * `texture` - wgpu texture to register (shared ownership).
	/// * `desc` - metadata copied into the entry (size, format, plane aspect,
	///   optional array layer range).
	fn register_texture_entry(
		&self,
		texture: Arc<wgpu::Texture>,
		desc: ImportedTextureDesc,
	) -> u64 {
		let token = self.next_token.fetch_add(1, Ordering::Relaxed);
		lock(&self.textures).insert(
			token,
			GpuTexture {
				texture,
				width: desc.width,
				height: desc.height,
				format: desc.format,
				aspect: desc.aspect,
				layer: desc.layer,
				#[cfg(any(target_os = "linux", target_os = "windows"))]
				external: None,
			keep_alive: None,
			},
		);
		token
	}

	/// The view for `token`, honoring plane aspects and array slices
	/// (M5 imports).
	pub(crate) fn texture_view(&self, token: u64) -> Result<wgpu::TextureView> {
		let entry = lock(&self.textures)
			.get(&token)
			.cloned()
			.ok_or(Error::NotFound)?;
		let (base_array_layer, array_layer_count) = match entry.layer {
			Some((base, count)) => (base, Some(count)),
			None => (0, None),
		};
		Ok(entry.texture.create_view(&wgpu::TextureViewDescriptor {
			aspect: entry.aspect,
			base_array_layer,
			array_layer_count,
			// wgpu-core derives `D2Array` from the TEXTURE's layer count,
			// not from the view range: an array-imported slice must ask
			// for `D2` explicitly or the planar pass's `D2` layout
			// validation rejects the bind group (M5 desktop review).
			dimension: (array_layer_count == Some(1)).then_some(wgpu::TextureViewDimension::D2),
			..Default::default()
		}))
	}
}

#[cfg(target_os = "linux")]
impl GpuContext {
	/// True when this context was configured for OpenFX GL zero-copy.
	pub fn ofx_zerocopy_enabled(&self) -> bool {
		self.ofx_zerocopy
	}

	/// True when the context is a Vulkan device that can export
	/// `OPAQUE_FD` memory (the Linux/OpenFX zero-copy prerequisite).
	pub fn supports_gl_zerocopy(&self) -> bool {
		self.ofx_zerocopy && unsafe { self.device.as_hal::<wgpu::hal::api::Vulkan>() }.is_some()
	}

	/// Creates an `Rgba32Float` texture backed by exportable Vulkan memory
	/// (`OPAQUE_FD`).
	///
	/// The returned token is registered exactly like
	/// `GpuContext::create_texture`, but carries an `ExternalTexture` that
	/// `GpuContext::export_gl_memory` can hand to the GL bridge. Any failure
	/// leaves no partial Vulkan objects and is reported to the caller, which
	/// falls back to a normal texture.
	///
	/// # Arguments
	///
	/// * `width` / `height` - texture size in pixels; must be positive.
	/// * `format` - must be `wgpu::TextureFormat::Rgba32Float`.
	/// * `usage` - must include `TextureUsages::TEXTURE_BINDING`.
	///
	/// # Errors
	///
	/// `Error::Invalid` for a non-positive size, a format other than RGBA32F, or
	/// a `usage` without texture binding; `Error::State` when the device is not
	/// Vulkan or the hal device cannot be acquired; `Error::Failed` when
	/// image/memory allocation or exporting the fd fails.
	pub fn create_exportable_texture(
		&self,
		width: i32,
		height: i32,
		format: wgpu::TextureFormat,
		usage: wgpu::TextureUsages,
	) -> Result<u64> {
		use ash::vk;
		use wgpu::hal;

		if width <= 0
			|| height <= 0
			|| format != wgpu::TextureFormat::Rgba32Float
			|| !usage.contains(wgpu::TextureUsages::TEXTURE_BINDING)
		{
			return Err(Error::Invalid);
		}
		let guard = unsafe { self.device.as_hal::<hal::api::Vulkan>() }.ok_or(Error::State)?;
		let hal_device: &hal::vulkan::Device = &guard;
		let raw = hal_device.raw_device().clone();

		let mut external = vk::ExternalMemoryImageCreateInfo::default()
			.handle_types(vk::ExternalMemoryHandleTypeFlags::OPAQUE_FD);
		let info = vk::ImageCreateInfo::default()
			.image_type(vk::ImageType::TYPE_2D)
			.format(vk::Format::R32G32B32A32_SFLOAT)
			.extent(vk::Extent3D {
				width: width as u32,
				height: height as u32,
				depth: 1,
			})
			.mip_levels(1)
			.array_layers(1)
			.samples(vk::SampleCountFlags::TYPE_1)
			.tiling(vk::ImageTiling::OPTIMAL)
			.usage(
				vk::ImageUsageFlags::SAMPLED
					| vk::ImageUsageFlags::COLOR_ATTACHMENT
					| vk::ImageUsageFlags::TRANSFER_SRC
					| vk::ImageUsageFlags::TRANSFER_DST,
			)
			.sharing_mode(vk::SharingMode::EXCLUSIVE)
			.initial_layout(vk::ImageLayout::UNDEFINED)
			.push_next(&mut external);
		let image = unsafe { raw.create_image(&info, None) }
			.map_err(|e| Error::Failed(format!("vkCreateImage(opaque-fd): {e:?}")))?;
		let req = unsafe { raw.get_image_memory_requirements(image) };

		let mut export = vk::ExportMemoryAllocateInfo::default()
			.handle_types(vk::ExternalMemoryHandleTypeFlags::OPAQUE_FD);
		let mut dedicated = vk::MemoryDedicatedAllocateInfo::default().image(image);
		let mut memory = None;
		let mut last_err = None;
		for type_index in 0..32u32 {
			if req.memory_type_bits & (1 << type_index) == 0 {
				continue;
			}
			let alloc = vk::MemoryAllocateInfo::default()
				.allocation_size(req.size)
				.memory_type_index(type_index)
				.push_next(&mut dedicated)
				.push_next(&mut export);
			match unsafe { raw.allocate_memory(&alloc, None) } {
				Ok(m) => {
					memory = Some(m);
					break;
				}
				Err(e) => last_err = Some((type_index, e)),
			}
		}
		let Some(memory) = memory else {
			unsafe { raw.destroy_image(image, None) };
			return Err(Error::Failed(format!(
				"vkAllocateMemory(opaque-fd) failed for every compatible type: {last_err:?}"
			)));
		};
		if let Err(e) = unsafe { raw.bind_image_memory(image, memory, 0) } {
			unsafe {
				raw.free_memory(memory, None);
				raw.destroy_image(image, None);
			}
			return Err(Error::Failed(format!("vkBindImageMemory: {e:?}")));
		}

		let fd = match ash_dispatch().and_then(|d| d.get_memory_fd(raw.handle())) {
			Some(get_fd) => {
				let info = vk::MemoryGetFdInfoKHR::default()
					.memory(memory)
					.handle_type(vk::ExternalMemoryHandleTypeFlags::OPAQUE_FD);
				let mut fd = -1;
				let res = unsafe { get_fd(raw.handle(), &info, &mut fd) };
				if res != vk::Result::SUCCESS || fd < 0 {
					None
				} else {
					Some(fd)
				}
			}
			None => None,
		};
		let Some(fd) = fd else {
			unsafe {
				raw.free_memory(memory, None);
				raw.destroy_image(image, None);
			}
			return Err(Error::Failed(
				"vkGetMemoryFdKHR(OPAQUE_FD) unavailable".into(),
			));
		};
		let fd = unsafe { OwnedFd::from_raw_fd(fd) };

		let hal_desc = hal::TextureDescriptor {
			label: Some("quercusrender-exportable-gl"),
			size: wgpu::Extent3d {
				width: width as u32,
				height: height as u32,
				depth_or_array_layers: 1,
			},
			mip_level_count: 1,
			sample_count: 1,
			dimension: wgpu::TextureDimension::D2,
			format,
			usage: wgpu_types::TextureUses::RESOURCE
				| wgpu_types::TextureUses::COLOR_TARGET
				| wgpu_types::TextureUses::COPY_SRC
				| wgpu_types::TextureUses::COPY_DST,
			memory_flags: hal::MemoryFlags::empty(),
			view_formats: Vec::new(),
		};
		let raw_guard = raw.clone();
		let drop_guard: hal::DropCallback = Box::new(move || unsafe {
			raw_guard.destroy_image(image, None);
			raw_guard.free_memory(memory, None);
		});
		let hal_texture = unsafe {
			hal_device.texture_from_raw(
				image,
				&hal_desc,
				Some(drop_guard),
				hal::vulkan::TextureMemory::External,
			)
		};
		let texture_desc = wgpu::TextureDescriptor {
			label: Some("quercusrender-exportable-gl"),
			size: wgpu::Extent3d {
				width: width as u32,
				height: height as u32,
				depth_or_array_layers: 1,
			},
			mip_level_count: 1,
			sample_count: 1,
			dimension: wgpu::TextureDimension::D2,
			format,
			usage,
			view_formats: &[],
		};
		let texture = unsafe {
			self.device
				.create_texture_from_hal::<hal::api::Vulkan>(hal_texture, &texture_desc)
		};
		self.used.store(true, Ordering::Release);
		let token = self.next_token.fetch_add(1, Ordering::Relaxed);
		lock(&self.textures).insert(
			token,
			GpuTexture {
				texture: Arc::new(texture),
				width: width as u32,
				height: height as u32,
				format,
				aspect: wgpu::TextureAspect::All,
				layer: None,
				external: Some(Arc::new(ExternalTexture {
					fd,
					size: req.size,
					width: width as u32,
					height: height as u32,
					format,
				})),
				keep_alive: None,
			},
		);
		Ok(token)
	}

	/// Export a texture token as an `OPAQUE_FD` GL memory object source.
	///
	/// Returns [`Error::State`] for a token that was not created through
	/// [`GpuContext::create_exportable_texture`] (the caller then uses the
	/// CPU/GL-readback path).
	pub fn export_gl_memory(&self, token: u64) -> Result<GlMemoryExport> {
		let entry = lock(&self.textures)
			.get(&token)
			.cloned()
			.ok_or(Error::NotFound)?;
		let external = entry.external.clone().ok_or(Error::State)?;
		Ok(GlMemoryExport {
			external,
			_texture: entry.texture,
		})
	}
}

#[cfg(target_os = "windows")]
impl GpuContext {
	/// True when this context was configured for OpenFX GL zero-copy.
	pub fn ofx_zerocopy_enabled(&self) -> bool {
		self.ofx_zerocopy
	}

	/// True when the context is a Vulkan device with
	/// `VK_KHR_external_memory_win32` enabled (the Windows prerequisites).
	pub fn supports_gl_zerocopy(&self) -> bool {
		self.ofx_zerocopy
			&& self
				.device
				.features()
				.contains(wgpu::Features::VULKAN_EXTERNAL_MEMORY_WIN32)
			&& unsafe { self.device.as_hal::<wgpu::hal::api::Vulkan>() }.is_some()
	}

	/// Creates an `Rgba32Float` texture backed by exportable Vulkan memory
	/// (`OPAQUE_WIN32`), the Windows counterpart of the Linux `OPAQUE_FD` path.
	///
	/// The returned token is registered like `GpuContext::create_texture` but
	/// carries an `ExternalTexture` that `GpuContext::export_gl_memory` can hand
	/// to the GL bridge. Any failure leaves no partial Vulkan objects behind.
	///
	/// # Arguments
	///
	/// * `width` / `height` - texture size in pixels; must be positive.
	/// * `format` - must be `wgpu::TextureFormat::Rgba32Float`.
	/// * `usage` - must include `TextureUsages::TEXTURE_BINDING`.
	///
	/// # Errors
	///
	/// `Error::Invalid` for a non-positive size, a format other than RGBA32F, or
	/// a `usage` without texture binding; `Error::State` when the device is not
	/// Vulkan or lacks `VULKAN_EXTERNAL_MEMORY_WIN32`; `Error::Failed` when
	/// image/memory allocation fails. The caller then falls back to a regular
	/// texture.
	pub fn create_exportable_texture(
		&self,
		width: i32,
		height: i32,
		format: wgpu::TextureFormat,
		usage: wgpu::TextureUsages,
	) -> Result<u64> {
		use ash::vk;
		use wgpu::hal;

		if width <= 0
			|| height <= 0
			|| format != wgpu::TextureFormat::Rgba32Float
			|| !usage.contains(wgpu::TextureUsages::TEXTURE_BINDING)
		{
			return Err(Error::Invalid);
		}
		if !self
			.device
			.features()
			.contains(wgpu::Features::VULKAN_EXTERNAL_MEMORY_WIN32)
		{
			return Err(Error::State);
		}
		let guard = unsafe { self.device.as_hal::<hal::api::Vulkan>() }.ok_or(Error::State)?;
		let hal_device: &hal::vulkan::Device = &guard;
		let raw = hal_device.raw_device().clone();

		let mut external = vk::ExternalMemoryImageCreateInfo::default()
			.handle_types(vk::ExternalMemoryHandleTypeFlags::OPAQUE_WIN32);
		let info = vk::ImageCreateInfo::default()
			.image_type(vk::ImageType::TYPE_2D)
			.format(vk::Format::R32G32B32A32_SFLOAT)
			.extent(vk::Extent3D {
				width: width as u32,
				height: height as u32,
				depth: 1,
			})
			.mip_levels(1)
			.array_layers(1)
			.samples(vk::SampleCountFlags::TYPE_1)
			.tiling(vk::ImageTiling::OPTIMAL)
			.usage(
				vk::ImageUsageFlags::SAMPLED
					| vk::ImageUsageFlags::COLOR_ATTACHMENT
					| vk::ImageUsageFlags::TRANSFER_SRC
					| vk::ImageUsageFlags::TRANSFER_DST,
			)
			.sharing_mode(vk::SharingMode::EXCLUSIVE)
			.initial_layout(vk::ImageLayout::UNDEFINED)
			.push_next(&mut external);
		let image = unsafe { raw.create_image(&info, None) }
			.map_err(|e| Error::Failed(format!("vkCreateImage(opaque-win32): {e:?}")))?;
		let req = unsafe { raw.get_image_memory_requirements(image) };

		let mut export = vk::ExportMemoryAllocateInfo::default()
			.handle_types(vk::ExternalMemoryHandleTypeFlags::OPAQUE_WIN32);
		let mut dedicated = vk::MemoryDedicatedAllocateInfo::default().image(image);
		let mut memory = None;
		let mut last_err = None;
		for type_index in 0..32u32 {
			if req.memory_type_bits & (1 << type_index) == 0 {
				continue;
			}
			let alloc = vk::MemoryAllocateInfo::default()
				.allocation_size(req.size)
				.memory_type_index(type_index)
				.push_next(&mut dedicated)
				.push_next(&mut export);
			match unsafe { raw.allocate_memory(&alloc, None) } {
				Ok(m) => {
					memory = Some(m);
					break;
				}
				Err(e) => last_err = Some((type_index, e)),
			}
		}
		let Some(memory) = memory else {
			unsafe { raw.destroy_image(image, None) };
			return Err(Error::Failed(format!(
				"vkAllocateMemory(opaque-win32) failed for every compatible type: {last_err:?}"
			)));
		};
		if let Err(e) = unsafe { raw.bind_image_memory(image, memory, 0) } {
			unsafe {
				raw.free_memory(memory, None);
				raw.destroy_image(image, None);
			}
			return Err(Error::Failed(format!("vkBindImageMemory: {e:?}")));
		}

		let handle = match ash_dispatch().and_then(|d| d.get_memory_win32_handle(raw.handle())) {
			Some(get_handle) => {
				let info = vk::MemoryGetWin32HandleInfoKHR::default()
					.memory(memory)
					.handle_type(vk::ExternalMemoryHandleTypeFlags::OPAQUE_WIN32);
				let mut handle: vk::HANDLE = 0;
				let res = unsafe { get_handle(raw.handle(), &info, &mut handle) };
				(res == vk::Result::SUCCESS && handle != 0).then_some(handle)
			}
			None => None,
		};
		let Some(handle) = handle else {
			unsafe {
				raw.free_memory(memory, None);
				raw.destroy_image(image, None);
			}
			return Err(Error::Failed(
				"vkGetMemoryWin32HandleKHR(OPAQUE_WIN32) unavailable".into(),
			));
		};

		let hal_desc = hal::TextureDescriptor {
			label: Some("quercusrender-exportable-gl"),
			size: wgpu::Extent3d {
				width: width as u32,
				height: height as u32,
				depth_or_array_layers: 1,
			},
			mip_level_count: 1,
			sample_count: 1,
			dimension: wgpu::TextureDimension::D2,
			format,
			usage: wgpu_types::TextureUses::RESOURCE
				| wgpu_types::TextureUses::COLOR_TARGET
				| wgpu_types::TextureUses::COPY_SRC
				| wgpu_types::TextureUses::COPY_DST,
			memory_flags: hal::MemoryFlags::empty(),
			view_formats: Vec::new(),
		};
		let raw_guard = raw.clone();
		let drop_guard: hal::DropCallback = Box::new(move || unsafe {
			raw_guard.destroy_image(image, None);
			raw_guard.free_memory(memory, None);
		});
		let hal_texture = unsafe {
			hal_device.texture_from_raw(
				image,
				&hal_desc,
				Some(drop_guard),
				hal::vulkan::TextureMemory::External,
			)
		};
		let texture_desc = wgpu::TextureDescriptor {
			label: Some("quercusrender-exportable-gl"),
			size: wgpu::Extent3d {
				width: width as u32,
				height: height as u32,
				depth_or_array_layers: 1,
			},
			mip_level_count: 1,
			sample_count: 1,
			dimension: wgpu::TextureDimension::D2,
			format,
			usage,
			view_formats: &[],
		};
		let texture = unsafe {
			self.device
				.create_texture_from_hal::<hal::api::Vulkan>(hal_texture, &texture_desc)
		};
		self.used.store(true, Ordering::Release);
		let token = self.next_token.fetch_add(1, Ordering::Relaxed);
		lock(&self.textures).insert(
			token,
			GpuTexture {
				texture: Arc::new(texture),
				width: width as u32,
				height: height as u32,
				format,
				aspect: wgpu::TextureAspect::All,
				layer: None,
				external: Some(Arc::new(ExternalTexture {
					handle,
					size: req.size,
					width: width as u32,
					height: height as u32,
					format,
				})),
				keep_alive: None,
			},
		);
		Ok(token)
	}

	/// Export a texture token as an `OPAQUE_WIN32` GL memory object source.
	pub fn export_gl_memory(&self, token: u64) -> Result<GlMemoryExport> {
		let entry = lock(&self.textures)
			.get(&token)
			.cloned()
			.ok_or(Error::NotFound)?;
		let external = entry.external.clone().ok_or(Error::State)?;
		Ok(GlMemoryExport {
			external,
			_texture: entry.texture,
		})
	}
}

#[cfg(not(any(target_os = "linux", target_os = "windows")))]
impl GpuContext {
	/// Other backends do not have the OpenFX GL zero-copy path yet.
	pub fn supports_gl_zerocopy(&self) -> bool {
		false
	}

	/// Other backends never request exportable textures.
	pub fn ofx_zerocopy_enabled(&self) -> bool {
		false
	}
}

#[cfg(test)]
mod tests {
	//! Unit coverage for the safe parts of the import module. The unsafe
	//! platform bodies are deliberately **not** exercised here: a real
	//! import needs a hardware decoder surface (a VAAPI DMA-BUF, a D3D11VA
	//! shared NT handle, a VideoToolbox IOSurface), which the
	//! software-Vulkan CI runners do not have, and feeding them fake
	//! handles would only assert that a driver rejects garbage.
	//!
	//! What covers the hardware paths instead:
	//! - `import_dmabuf_plane` (Linux): a VAAPI machine running
	//!   `quercus-render/tests/footage_import_test.rs` (DMA-BUF + DRM format
	//!   modifier import); the M5 real-hardware acceptance is recorded in
	//!   `docs/zh/plans/render-pipeline-threads-m5-branch-coverage.txt`.
	//! - `import_d3d11_shared_texture` (Windows): the Windows job on a host
	//!   with D3D11VA; a lavapipe-only runner has no shared texture to
	//!   import and the decode side falls back to staging.
	//! - `import_iosurface_plane` (macOS): the macOS job with VideoToolbox
	//!   active.
	//! - `register_imported_texture*`/`texture_view`: the alias registry
	//!   and view helper are unit-tested below on a locally created array
	//!   texture (no platform import); the `Plane0`/`Plane1` aspects only
	//!   become valid with the multi-planar formats of a real import.

	use super::*;
	use crate::backend::gpu_or_skip;
	use crate::error::Error;

	/// The Linux plane format map accepts exactly the luma/chroma planes
	/// the planar import feeds it and rejects everything else.
	#[cfg(target_os = "linux")]
	#[test]
	fn import_vk_format_maps_luma_and_chroma_planes() {
		use ash::vk::Format;
		assert_eq!(
			import_vk_format(wgpu::TextureFormat::R8Unorm),
			Some(Format::R8_UNORM)
		);
		assert_eq!(
			import_vk_format(wgpu::TextureFormat::Rg8Unorm),
			Some(Format::R8G8_UNORM)
		);
		assert_eq!(
			import_vk_format(wgpu::TextureFormat::R16Unorm),
			Some(Format::R16_UNORM)
		);
		assert_eq!(
			import_vk_format(wgpu::TextureFormat::Rg16Unorm),
			Some(Format::R16G16_UNORM)
		);
		for rejected in [
			wgpu::TextureFormat::Rgba8Unorm,
			wgpu::TextureFormat::Rgba32Float,
			wgpu::TextureFormat::NV12,
			wgpu::TextureFormat::P010,
		] {
			assert_eq!(
				import_vk_format(rejected),
				None,
				"{rejected:?} is not a single-plane sample format"
			);
		}
	}

	/// The macOS plane map accepts the interleaved 8/16-bit layouts the
	/// VideoToolbox import feeds and rejects everything else.
	#[cfg(target_os = "macos")]
	#[test]
	fn iosurface_pixel_format_maps_supported_planes() {
		use objc2_metal::MTLPixelFormat;
		assert_eq!(
			iosurface_pixel_format(wgpu::TextureFormat::R8Unorm),
			Some(MTLPixelFormat::R8Unorm)
		);
		assert_eq!(
			iosurface_pixel_format(wgpu::TextureFormat::Rg8Unorm),
			Some(MTLPixelFormat::RG8Unorm)
		);
		assert_eq!(
			iosurface_pixel_format(wgpu::TextureFormat::R16Unorm),
			Some(MTLPixelFormat::R16Unorm)
		);
		assert_eq!(
			iosurface_pixel_format(wgpu::TextureFormat::Rg16Unorm),
			Some(MTLPixelFormat::RG16Unorm)
		);
		assert_eq!(
			iosurface_pixel_format(wgpu::TextureFormat::Rgba8Unorm),
			None
		);
	}

	/// `import_dmabuf_plane`'s argument validation must reject zero-sized
	/// imports and non-plane formats *before* it touches Vulkan, so this
	/// runs without any DMA-BUF: the plane fd (here invalid on purpose)
	/// is never reached.
	#[cfg(target_os = "linux")]
	#[test]
	fn dmabuf_import_rejects_invalid_arguments_without_importing() {
		let Some(ctx) = gpu_or_skip("the DMA-BUF argument validation test") else {
			return;
		};
		if ctx.kind() != crate::backend::BackendKind::Vulkan {
			eprintln!("SKIP: the DMA-BUF validation test needs a Vulkan context");
			return;
		}
		let plane = DmaBufPlane {
			fd: -1,
			offset: 0,
			pitch: 64,
			modifier: 0,
		};
		let err = ctx
			.import_dmabuf_plane(0, 64, wgpu::TextureFormat::R8Unorm, plane, None)
			.unwrap_err();
		assert!(matches!(err, Error::State), "zero width: {err:?}");
		let err = ctx
			.import_dmabuf_plane(64, 0, wgpu::TextureFormat::R8Unorm, plane, None)
			.unwrap_err();
		assert!(matches!(err, Error::State), "zero height: {err:?}");
		let err = ctx
			.import_dmabuf_plane(64, 64, wgpu::TextureFormat::Bgra8Unorm, plane, None)
			.unwrap_err();
		assert!(matches!(err, Error::Invalid), "non-plane format: {err:?}");
	}

	/// The registry/view helper every import shares: one array texture,
	/// several aliases. A single-slice alias must produce the explicit `D2`
	/// view the M5 desktop review fix requests (wgpu-core would otherwise
	/// derive `D2Array` from the texture's layer count) **and bind into the
	/// planar pass's `D2` bind-group layout** — the actual failure point of
	/// that regression: `create_view` succeeds on a derived `D2Array`, the
	/// bind group does not. Broader aliases keep the array dimension (and
	/// are shown to be rejected by the `D2` layout, so the guard is
	/// falsifiable), and unknown tokens are `NotFound`.
	#[test]
	fn imported_texture_aliases_create_valid_views_and_bind() {
		let Some(ctx) = gpu_or_skip("the imported-texture alias test") else {
			return;
		};
		// The shape a D3D11VA import registers: one 4-layer D2 texture.
		let texture = Arc::new(ctx.device.create_texture(&wgpu::TextureDescriptor {
			label: Some("quercusrender-imported-test"),
			size: wgpu::Extent3d {
				width: 8,
				height: 8,
				depth_or_array_layers: 4,
			},
			mip_level_count: 1,
			sample_count: 1,
			dimension: wgpu::TextureDimension::D2,
			format: wgpu::TextureFormat::Rgba8Unorm,
			usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
			view_formats: &[],
		}));
		let desc = ImportedTextureDesc {
			width: 8,
			height: 8,
			array_layers: 4,
			format: wgpu::TextureFormat::Rgba8Unorm,
			aspect: wgpu::TextureAspect::All,
			layer: Some((2, 1)),
		};
		let single = ctx.register_texture_entry(texture.clone(), desc);
		let single_view = ctx.texture_view(single).expect("single-slice alias view");

		let pair = ctx.register_texture_entry(
			texture.clone(),
			ImportedTextureDesc {
				layer: Some((0, 2)),
				..desc
			},
		);
		let pair_view = ctx.texture_view(pair).expect("two-slice alias view");

		let whole = ctx.register_texture_entry(
			texture.clone(),
			ImportedTextureDesc {
				layer: None,
				..desc
			},
		);
		ctx.texture_view(whole).expect("whole-array alias view");

		assert_ne!(single, pair, "aliases get distinct tokens");
		assert_ne!(pair, whole, "aliases get distinct tokens");
		assert!(
			matches!(ctx.texture_view(u64::MAX), Err(Error::NotFound)),
			"an unregistered token must be NotFound"
		);

		// The regression guard: the planar pass creates its bind group
		// with a `D2` layout. Without `dimension: Some(D2)` the
		// single-slice alias is a derived `D2Array` and this bind group
		// fails validation, so the test must exercise bind-group creation
		// (not just `create_view`). Use the production planar layout so the
		// guard follows it if the layout changes.
		let pipeline = ctx
			.planar_yuv_pipeline()
			.expect("the planar pass pipeline builds");
		// The chroma slot must be a single-slice `D2` alias too: slice 0 of
		// the same texture serves.
		let chroma = ctx.register_texture_entry(
			texture,
			ImportedTextureDesc {
				layer: Some((0, 1)),
				..desc
			},
		);
		let chroma_view = ctx.texture_view(chroma).expect("chroma alias view");
		let uniform = ctx.device.create_buffer(&wgpu::BufferDescriptor {
			label: Some("quercusrender-imported-test-planar-params"),
			size: 64,
			usage: wgpu::BufferUsages::UNIFORM,
			mapped_at_creation: false,
		});
		let scope = ctx.device.push_error_scope(wgpu::ErrorFilter::Validation);
		let _bind_group = ctx.device.create_bind_group(&wgpu::BindGroupDescriptor {
			label: Some("quercusrender-imported-test-planar-bg"),
			layout: &pipeline.layout,
			entries: &[
				wgpu::BindGroupEntry {
					binding: 0,
					resource: wgpu::BindingResource::TextureView(&single_view),
				},
				wgpu::BindGroupEntry {
					binding: 1,
					resource: wgpu::BindingResource::TextureView(&chroma_view),
				},
				wgpu::BindGroupEntry {
					binding: 2,
					resource: uniform.as_entire_binding(),
				},
			],
		});
		let error = pollster_block_on(scope.pop());
		assert!(
			error.is_none(),
			"single-slice aliases must bind into the planar pass's D2 layout \
			 (a D2Array view is rejected here): {error:?}"
		);

		// Negative control: the broader (D2Array) alias is rejected by the
		// same layout, proving mismatch in the assertion above is
		// observable through the error scope.
		let scope = ctx.device.push_error_scope(wgpu::ErrorFilter::Validation);
		let _rejected = ctx.device.create_bind_group(&wgpu::BindGroupDescriptor {
			label: Some("quercusrender-imported-test-planar-bg-rejected"),
			layout: &pipeline.layout,
			entries: &[
				wgpu::BindGroupEntry {
					binding: 0,
					resource: wgpu::BindingResource::TextureView(&pair_view),
				},
				wgpu::BindGroupEntry {
					binding: 1,
					resource: wgpu::BindingResource::TextureView(&chroma_view),
				},
				wgpu::BindGroupEntry {
					binding: 2,
					resource: uniform.as_entire_binding(),
				},
			],
		});
		let error = pollster_block_on(scope.pop());
		assert!(
			error.is_some(),
			"a D2Array alias must be rejected by the D2 planar layout"
		);
	}

	/// Windows OpenFX zero-copy prerequisite: an `Rgba32Float` texture
	/// created through the exportable path carries a live NT handle.
	#[cfg(target_os = "windows")]
	#[test]
	fn exportable_texture_exports_opaque_win32_handle() {
		let Some(ctx) = gpu_or_skip("exportable win32 texture") else {
			return;
		};
		if !ctx.supports_gl_zerocopy() {
			eprintln!("SKIP: context is not Vulkan / Win32 external memory disabled");
			return;
		}
		let token = ctx
			.create_exportable_texture(
				64,
				64,
				wgpu::TextureFormat::Rgba32Float,
				wgpu::TextureUsages::TEXTURE_BINDING
					| wgpu::TextureUsages::RENDER_ATTACHMENT
					| wgpu::TextureUsages::COPY_SRC
					| wgpu::TextureUsages::COPY_DST,
			)
			.expect("exportable texture");
		let export = ctx.export_gl_memory(token).expect("gl memory export");
		assert_eq!(export.width(), 64);
		assert_eq!(export.height(), 64);
		assert!(export.size() >= 64 * 64 * 16);
		let handle = export.try_clone_handle().expect("duplicate opaque handle");
		assert!(handle != 0);
		ctx.destroy_texture(token);
	}

	/// Linux OpenFX zero-copy prerequisite: an `Rgba32Float` texture
	/// created through the exportable path carries a live `OPAQUE_FD`.
	/// Real GL import is covered by the OFX plugin integration test; this
	/// test only proves the Vulkan export half.
	#[cfg(target_os = "linux")]
	#[test]
	fn exportable_texture_exports_opaque_fd() {
		use std::os::fd::AsRawFd;
		let Some(ctx) = gpu_or_skip("exportable texture") else {
			return;
		};
		if !ctx.supports_gl_zerocopy() {
			eprintln!("SKIP: context is not Vulkan / zero-copy disabled");
			return;
		}
		let token = ctx
			.create_exportable_texture(
				64,
				64,
				wgpu::TextureFormat::Rgba32Float,
				wgpu::TextureUsages::TEXTURE_BINDING
					| wgpu::TextureUsages::RENDER_ATTACHMENT
					| wgpu::TextureUsages::COPY_SRC
					| wgpu::TextureUsages::COPY_DST,
			)
			.expect("exportable texture");
		let export = ctx.export_gl_memory(token).expect("gl memory export");
		assert_eq!(export.width(), 64);
		assert_eq!(export.height(), 64);
		assert!(export.size() >= 64 * 64 * 16);
		let fd = export.try_clone_fd().expect("dup opaque fd");
		assert!(fd.as_raw_fd() >= 0);
		ctx.destroy_texture(token);
	}
}