edgefirst-tensor 0.32.0

Zero-copy tensor memory management with DMA, shared memory, and heap backends
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
// SPDX-FileCopyrightText: Copyright 2026 Au-Zone Technologies
// SPDX-License-Identifier: Apache-2.0

//! IOSurface-backed tensor storage for macOS.
//!
//! `IoSurfaceTensor<T>` is the macOS counterpart to `DmaTensor<T>` on
//! Linux: a zero-copy GPU↔CPU buffer that the OpenGL backend (ANGLE on
//! macOS) can import directly via `EGL_ANGLE_iosurface_client_buffer`.
//! Both fit into the `TensorMemory::DmaBuf` slot — the variant name is
//! shared, the inner storage type differs per platform.
//!
//! ## Bindings approach
//!
//! Raw FFI to the IOSurface and CoreFoundation frameworks (linked via
//! `#[link]`). The `objc2-io-surface` crate's Obj-C wrappers want
//! `NSDictionary` for properties and don't accept CFDictionary cleanly
//! through their `initWithProperties` API; the C IOSurface API takes
//! `CFDictionaryRef` directly, which is what we have to hand and what
//! the spike at `spikes/angle_iosurface/` validates.
//!
//! ## CPU access
//!
//! `map()` returns `IoSurfaceMap<T>` which holds an `IOSurfaceLock` and
//! exposes the base address as a slice. `unmap()`/`Drop` calls the
//! matching unlock. IOSurface handles GPU↔CPU cache coherency
//! implicitly — no separate `DMA_BUF_IOCTL_SYNC` analog needed.
//!
//! ## Cross-process sharing
//!
//! IOSurfaces are identified by `IOSurfaceID` (u32) within a host. The
//! GL backend uses this id as part of the buffer-identity cache key so
//! repeated frames for the same IOSurface reuse the EGL pbuffer import.
//! Full Mach port passing is deferred.

#![cfg(any(target_os = "macos", target_os = "ios"))]

use crate::{
    error::{Error, Result},
    packed_rgba16f_layout, BufferIdentity, DType, IdentityKind, PixelFormat, TensorMemory,
    TensorTrait,
};
use log::trace;
use num_traits::Num;
use std::{ffi::c_void, fmt, marker::PhantomData, ptr::NonNull, sync::Arc};

// ---------------------------------------------------------------------------
// Raw FFI to IOSurface + CoreFoundation
// ---------------------------------------------------------------------------

type IOSurfaceRef = *mut c_void;
type CFDictionaryRef = *mut c_void;
type CFStringRef = *mut c_void;
type CFNumberRef = *mut c_void;

const K_CF_NUMBER_LONG_TYPE: i32 = 10; // kCFNumberLongType
const K_CF_STRING_ENCODING_UTF8: u32 = 0x08000100;

// IOSurface lock options.
const K_IOSURFACE_LOCK_READ_ONLY: u32 = 0x01;
#[allow(dead_code)]
const K_IOSURFACE_LOCK_AVOID_SYNC: u32 = 0x02;

// IOSurface depends on CoreFoundation for the CFDictionary properties
// dict and CFNumber values. Both frameworks must be linked explicitly:
// clippy warns about the duplicate `kind` attribute but it's required —
// each framework is its own dylib.
#[allow(clippy::duplicated_attributes)]
#[link(name = "IOSurface", kind = "framework")]
#[link(name = "CoreFoundation", kind = "framework")]
extern "C" {
    fn IOSurfaceCreate(properties: CFDictionaryRef) -> IOSurfaceRef;
    fn IOSurfaceLock(surface: IOSurfaceRef, options: u32, seed: *mut u32) -> i32;
    fn IOSurfaceUnlock(surface: IOSurfaceRef, options: u32, seed: *mut u32) -> i32;
    fn IOSurfaceGetBaseAddress(surface: IOSurfaceRef) -> *mut c_void;
    fn IOSurfaceGetAllocSize(surface: IOSurfaceRef) -> usize;
    fn IOSurfaceGetBytesPerRow(surface: IOSurfaceRef) -> usize;
    fn IOSurfaceGetWidth(surface: IOSurfaceRef) -> usize;
    fn IOSurfaceGetHeight(surface: IOSurfaceRef) -> usize;
    fn IOSurfaceGetID(surface: IOSurfaceRef) -> u32;
    fn IOSurfaceLookup(csid: u32) -> IOSurfaceRef;

    fn CFRetain(cf: *const c_void) -> *const c_void;
    fn CFRelease(cf: *const c_void);
    // Called only from `#[cfg(test)]` retain-count assertions. The lib
    // target (what iOS clippy `-D warnings` sees first) would otherwise
    // trip `dead_code`.
    #[cfg_attr(not(test), expect(dead_code))]
    fn CFGetRetainCount(cf: *const c_void) -> isize;

    fn CFDictionaryCreateMutable(
        allocator: *const c_void,
        capacity: isize,
        key_callbacks: *const c_void,
        value_callbacks: *const c_void,
    ) -> CFDictionaryRef;
    fn CFDictionarySetValue(dict: CFDictionaryRef, key: *const c_void, value: *const c_void);
    fn CFStringCreateWithCString(
        allocator: *const c_void,
        cstr: *const i8,
        encoding: u32,
    ) -> CFStringRef;
    fn CFNumberCreate(allocator: *const c_void, ty: i32, value_ptr: *const c_void) -> CFNumberRef;

    static kCFTypeDictionaryKeyCallBacks: c_void;
    static kCFTypeDictionaryValueCallBacks: c_void;
}

/// Derive a [`BufferIdentity`] from `IOSurfaceGetID`.
///
/// The id is the system's own identifier for the surface, stable across
/// every wrap of it within a host. Without deriving from it, two
/// independently-linked copies of this crate (or a re-wrap crossing a
/// library boundary, e.g. a producer handing off an `IOSurfaceID`) would
/// disagree on the identity, and the GL backend's EGLImage import cache
/// would miss -- re-importing the same surface every frame instead of
/// reusing the bound pbuffer.
fn identity_from_surface(surface: IOSurfaceRef) -> BufferIdentity {
    let id = unsafe { IOSurfaceGetID(surface) };
    BufferIdentity::derived(IdentityKind::IoSurface, id as u64)
}

/// Owned IOSurface handle. Releases on Drop via `CFRelease`. Cloneable
/// via Arc — every clone shares the same underlying surface.
#[derive(Debug, Clone)]
pub(crate) struct OwnedIoSurface {
    inner: Arc<IoSurfaceHandle>,
}

/// Inner wrapper that handles the actual CFRelease in Drop. Wrapping in
/// Arc means multiple clones of `OwnedIoSurface` share the same retain
/// count and the surface is released exactly once when the last clone
/// drops.
#[derive(Debug)]
struct IoSurfaceHandle(IOSurfaceRef);

unsafe impl Send for IoSurfaceHandle {}
unsafe impl Sync for IoSurfaceHandle {}

impl Drop for IoSurfaceHandle {
    fn drop(&mut self) {
        if !self.0.is_null() {
            unsafe { CFRelease(self.0 as *const c_void) };
        }
    }
}

impl OwnedIoSurface {
    /// Take ownership of an `IOSurfaceRef` returned by `IOSurfaceCreate`.
    /// The caller must not call `CFRelease` on the ref after this.
    fn from_created(ptr: IOSurfaceRef) -> Result<Self> {
        if ptr.is_null() {
            return Err(Error::IoError(std::io::Error::other(
                "IOSurfaceCreate returned null",
            )));
        }
        Ok(Self {
            inner: Arc::new(IoSurfaceHandle(ptr)),
        })
    }

    /// Wrap an externally-owned `IOSurfaceRef`. Calls `CFRetain` so the
    /// surface is kept alive while this `OwnedIoSurface` exists; the
    /// caller's reference is independent.
    pub(crate) fn from_external(ptr: IOSurfaceRef) -> Result<Self> {
        if ptr.is_null() {
            return Err(Error::InvalidArgument(
                "from_external: null IOSurfaceRef".into(),
            ));
        }
        unsafe { CFRetain(ptr as *const c_void) };
        Ok(Self {
            inner: Arc::new(IoSurfaceHandle(ptr)),
        })
    }

    pub(crate) fn as_ptr(&self) -> IOSurfaceRef {
        self.inner.0
    }
}

/// Recover a live `IOSurfaceRef` from a cross-process/cross-package
/// IOSurfaceID — the identifier `Tensor::iosurface_id` reports and that
/// [`crate::protocol::TensorDesc::handle`] carries for
/// [`crate::protocol::kind::IOSURFACE`] descriptors.
///
/// `IOSurfaceLookup` hands back a new (+1) reference the caller owns; this
/// is why every call site pairs a successful lookup with [`release`] once
/// it has taken (or failed to take) its own independent retain, e.g. via
/// [`OwnedIoSurface::from_external`]'s `CFRetain`.
///
/// Returns `None` when no live surface has that id — a stale id, or a
/// surface whose producer already released it (the descriptor's borrow
/// contract was violated, or the capsule outlived its keepalive).
pub(crate) fn lookup_by_id(id: u32) -> Option<*mut c_void> {
    let ptr = unsafe { IOSurfaceLookup(id) };
    if ptr.is_null() {
        None
    } else {
        Some(ptr)
    }
}

/// Release a `+1` `IOSurfaceRef` obtained from [`lookup_by_id`].
pub(crate) fn release(ptr: *mut c_void) {
    unsafe { CFRelease(ptr as *const c_void) };
}

// ---------------------------------------------------------------------------
// IoSurfaceTensor — fits into TensorStorage::Dma on macOS.
// ---------------------------------------------------------------------------

#[derive(Debug)]
pub struct IoSurfaceTensor<T>
where
    T: Num + Clone + fmt::Debug + Send + Sync,
{
    pub name: String,
    pub(crate) surface: OwnedIoSurface,
    pub shape: Vec<usize>,
    pub _marker: PhantomData<T>,
    identity: BufferIdentity,
    /// Total bytes allocated by the IOSurface (from `IOSurfaceGetAllocSize`).
    pub(crate) buf_size: usize,
    /// Row pitch in bytes (from `IOSurfaceGetBytesPerRow`). IOSurface rounds
    /// this up to 64-byte alignment, so for image-formatted surfaces it can
    /// exceed the natural `width × bytes_per_pixel`. Image-formatted tensors
    /// carry this as their row stride so CPU consumers iterate rows correctly;
    /// raw byte surfaces (`new_with_byte_size`, a single padded row) leave the
    /// tensor stride natural.
    pub(crate) bytes_per_row: usize,
    /// Whether this tensor was constructed from an externally-provided
    /// IOSurface via `from_surface`. Mirrors `DmaTensor::is_imported`
    /// and is reserved for diagnostic and C-API parity uses. Not yet
    /// consumed by any decision logic on macOS — IOSurface lifecycle is
    /// CFRetain/CFRelease symmetric regardless of import origin.
    #[allow(dead_code)]
    pub(crate) is_imported: bool,
    /// Byte offset of this tensor's window into the shared IOSurface. Non-zero
    /// only for sub-views (`view`/`batch`), which share the surface + identity
    /// and address a sub-region by this offset — mirrors `DmaTensor::mmap_offset`.
    /// CPU maps add it to the locked base address; the GL path keys the import
    /// on the parent identity and renders the sub-region via `glViewport`.
    pub(crate) view_offset: usize,
}

unsafe impl<T> Send for IoSurfaceTensor<T> where T: Num + Clone + fmt::Debug + Send + Sync {}
unsafe impl<T> Sync for IoSurfaceTensor<T> where T: Num + Clone + fmt::Debug + Send + Sync {}

/// Keepalive holding an IOSurface's CPU lock for a map's lifetime.
///
/// `host_pin` deliberately takes no lock — an IOSurface address is stable
/// without one. A *map* is different: it promises coherent CPU access for its
/// duration, so it locks here and unlocks on drop, replaying the SAME options
/// as the lock (Apple requires the pair to match, which is why the options are
/// stored rather than re-derived).
pub(crate) struct IoSurfaceMapLock {
    surface: OwnedIoSurface,
    options: u32,
}

impl Drop for IoSurfaceMapLock {
    fn drop(&mut self) {
        let mut seed: u32 = 0;
        let rc = unsafe { IOSurfaceUnlock(self.surface.as_ptr(), self.options, &mut seed) };
        if rc != 0 {
            log::error!("IOSurfaceUnlock failed (rc={rc})");
        }
    }
}

/// Lock options for a CPU access direction.
///
/// A read-only lock skips the cache flush at unlock — the caller promised not
/// to write, so there is nothing to publish to the GPU. Apple requires the
/// options passed to `IOSurfaceUnlock` to MATCH the ones passed to
/// `IOSurfaceLock`, which is precisely why both halves of the sync API take the
/// direction rather than inferring it.
fn lock_options(access: crate::CpuAccess) -> u32 {
    if access.writes() {
        0
    } else {
        K_IOSURFACE_LOCK_READ_ONLY
    }
}

impl<T> IoSurfaceTensor<T>
where
    T: Num + Clone + fmt::Debug + Send + Sync,
{
    /// Establish a persistent host address for this surface.
    ///
    /// Takes **no lock**: `IOSurfaceGetBaseAddress` is stable for the
    /// surface's lifetime, and the lock is a coherency window, not an
    /// addressing one. Separating them is the whole point — the surface is
    /// retained as the pin's keepalive, so the address outlives any guard.
    pub(crate) fn host_pin<'a>(&self) -> crate::Result<crate::pin::HostPin<'a>>
    where
        T: 'a,
    {
        let base = unsafe { IOSurfaceGetBaseAddress(self.surface.as_ptr()) };
        let base_ptr = NonNull::new(base).ok_or_else(|| {
            Error::IoError(std::io::Error::other(
                "IOSurfaceGetBaseAddress returned null; surface is not host-addressable",
            ))
        })?;
        // The whole surface; Tensor::pin_host narrows to the logical extent.
        // IOSurface rounds its row pitch to 64 bytes, so this is wider than the
        // logical size for image-formatted surfaces -- which is exactly what a
        // map guard needs to expose padded rows.
        let len = self.buf_size;
        Ok(crate::pin::HostPin::new(
            std::sync::Arc::new(self.surface.clone()),
            base_ptr.as_ptr() as *mut u8,
            len,
        ))
    }
}

impl<T> IoSurfaceTensor<T>
where
    T: Num + Clone + fmt::Debug + Send + Sync,
{
    /// Shared map constructor: lock via `scoped_pin` (released by the pin's
    /// keepalive on drop, with the same options at unlock as at lock) and wrap
    /// the result in the collapsed view.
    fn map_inner<'a>(
        &self,
        byte_size_override: Option<usize>,
        access: crate::CpuAccess,
    ) -> Result<crate::view::HostView<'a, T>>
    where
        T: 'a,
    {
        let exposed = match byte_size_override {
            Some(bytes) => bytes,
            None => self.shape.iter().product::<usize>() * std::mem::size_of::<T>(),
        };
        let end = self
            .view_offset
            .checked_add(exposed)
            .ok_or(Error::InvalidSize(exposed))?;
        if end > self.buf_size {
            return Err(Error::InsufficientCapacity {
                needed: end,
                capacity: self.buf_size,
            });
        }
        Ok(crate::view::HostView::new(
            self.scoped_pin(access)?,
            self.shape.clone(),
            byte_size_override,
            access,
        ))
    }

    /// Lock the surface and pin its address for the resulting view's lifetime.
    ///
    /// Unlike [`host_pin`](Self::host_pin), which takes no lock, this is the
    /// map path: the lock is held until the pin's keepalive drops.
    pub(crate) fn scoped_pin<'a>(&self, access: crate::CpuAccess) -> Result<crate::pin::HostPin<'a>>
    where
        T: 'a,
    {
        let options = lock_options(access);
        let mut seed: u32 = 0;
        let rc = unsafe { IOSurfaceLock(self.surface.as_ptr(), options, &mut seed) };
        if rc != 0 {
            return Err(Error::IoError(std::io::Error::other(format!(
                "IOSurfaceLock failed (rc={rc})"
            ))));
        }
        let keepalive = std::sync::Arc::new(IoSurfaceMapLock {
            surface: self.surface.clone(),
            options,
        });
        let base = unsafe { IOSurfaceGetBaseAddress(self.surface.as_ptr()) };
        let base_ptr = NonNull::new(base).ok_or_else(|| {
            Error::IoError(std::io::Error::other(
                "IOSurfaceGetBaseAddress returned null after lock",
            ))
        })?;
        // SAFETY: the sole caller, `map_inner`, refuses `view_offset + exposed`
        // past `buf_size` before it gets here, so this stays inside the
        // surface's allocation.
        let data = unsafe { (base_ptr.as_ptr() as *mut u8).add(self.view_offset) };
        let len = self.buf_size.saturating_sub(self.view_offset);
        Ok(crate::pin::HostPin::new(keepalive, data, len))
    }

    /// `IOSurfaceLock` — the CPU is about to access the surface.
    pub(crate) fn sync_for_cpu(&self, access: crate::CpuAccess) -> crate::Result<()> {
        let mut seed: u32 = 0;
        let rc = unsafe { IOSurfaceLock(self.surface.as_ptr(), lock_options(access), &mut seed) };
        if rc != 0 {
            return Err(Error::IoError(std::io::Error::other(format!(
                "IOSurfaceLock failed (rc={rc})"
            ))));
        }
        Ok(())
    }

    /// `IOSurfaceUnlock` — the CPU is done. Options must match the lock.
    pub(crate) fn sync_for_device(&self, access: crate::CpuAccess) -> crate::Result<()> {
        let mut seed: u32 = 0;
        let rc = unsafe { IOSurfaceUnlock(self.surface.as_ptr(), lock_options(access), &mut seed) };
        if rc != 0 {
            return Err(Error::IoError(std::io::Error::other(format!(
                "IOSurfaceUnlock failed (rc={rc})"
            ))));
        }
        Ok(())
    }
}

impl<T> TensorTrait<T> for IoSurfaceTensor<T>
where
    T: Num + Clone + fmt::Debug + Send + Sync,
{
    fn new(shape: &[usize], name: Option<&str>) -> Result<Self> {
        let byte_size = shape
            .iter()
            .product::<usize>()
            .saturating_mul(std::mem::size_of::<T>());
        Self::new_with_byte_size(shape, byte_size, name)
    }

    fn from_fd(_fd: std::os::fd::OwnedFd, _shape: &[usize], _name: Option<&str>) -> Result<Self> {
        Err(Error::NotImplemented(
            "IoSurfaceTensor::from_fd: IOSurface is not fd-backed; use from_surface()".into(),
        ))
    }

    fn clone_fd(&self) -> Result<std::os::fd::OwnedFd> {
        Err(Error::NotImplemented(
            "IoSurfaceTensor::clone_fd: use surface_id() for cross-process sharing".into(),
        ))
    }

    fn memory(&self) -> TensorMemory {
        // Unified variant: macOS reports Dma, same as Linux. The variant
        // name is shared; the inner storage type differs per platform.
        TensorMemory::DmaBuf
    }

    fn name(&self) -> String {
        self.name.clone()
    }

    fn shape(&self) -> &[usize] {
        &self.shape
    }

    fn reshape(&mut self, shape: &[usize]) -> Result<()> {
        let new_elems: usize = shape.iter().product();
        let cur_elems: usize = self.shape.iter().product();
        if new_elems != cur_elems {
            return Err(Error::InvalidShape(format!(
                "reshape: element count mismatch ({cur_elems} → {new_elems})",
            )));
        }
        self.shape = shape.to_vec();
        self.view_offset = 0;
        Ok(())
    }

    fn map_with<'a>(&self, access: crate::CpuAccess) -> Result<crate::view::HostView<'a, T>>
    where
        T: 'a,
    {
        let _span = tracing::trace_span!("tensor.map", memory = "iosurface", ?access).entered();
        self.map_inner(None, access)
    }

    fn buffer_identity(&self) -> &BufferIdentity {
        &self.identity
    }

    fn capacity_bytes(&self) -> usize {
        self.buf_size
    }

    fn set_logical_shape(&mut self, shape: &[usize]) -> Result<()> {
        if shape.is_empty() {
            return Err(Error::InvalidSize(0));
        }
        let needed = shape.iter().product::<usize>() * std::mem::size_of::<T>();
        if needed > self.buf_size {
            return Err(Error::InsufficientCapacity {
                needed,
                capacity: self.buf_size,
            });
        }
        self.shape = shape.to_vec();
        Ok(())
    }

    /// Zero-copy sub-region view sharing this surface (CFRetain via the
    /// `Arc`-backed `OwnedIoSurface`) and [`BufferIdentity`], positioned at
    /// `offset_bytes` from this tensor's own window with logical `shape`. The
    /// GL backend keys the IOSurface import on the shared identity and renders
    /// the sub-region via `glViewport`; a CPU map adds `view_offset` to the
    /// locked base address. Mirrors [`DmaTensor::view`](crate::TensorTrait::view).
    ///
    /// # Errors
    ///
    /// - [`Error::InvalidOperation`] if `offset_bytes` is mis-aligned for `T`.
    /// - [`Error::InsufficientCapacity`] if the window exceeds the surface.
    fn view(&self, offset_bytes: usize, shape: &[usize]) -> Result<Self> {
        if !offset_bytes.is_multiple_of(std::mem::align_of::<T>()) {
            return Err(Error::InvalidOperation(format!(
                "IoSurfaceTensor::view: offset {offset_bytes} not aligned to align_of::<T>()={}",
                std::mem::align_of::<T>()
            )));
        }
        let abs_offset = self
            .view_offset
            .checked_add(offset_bytes)
            .ok_or(Error::InvalidSize(offset_bytes))?;
        let logical = shape.iter().product::<usize>() * std::mem::size_of::<T>();
        let needed = abs_offset
            .checked_add(logical)
            .ok_or(Error::InvalidSize(logical))?;
        if needed > self.buf_size {
            return Err(Error::InsufficientCapacity {
                needed,
                capacity: self.buf_size,
            });
        }
        Ok(Self {
            name: self.name.clone(),
            surface: self.surface.clone(),
            shape: shape.to_vec(),
            _marker: PhantomData,
            identity: self.identity.clone(),
            buf_size: self.buf_size,
            bytes_per_row: self.bytes_per_row,
            is_imported: self.is_imported,
            view_offset: abs_offset,
        })
    }
}

impl<T> IoSurfaceTensor<T>
where
    T: Num + Clone + fmt::Debug + Send + Sync,
{
    /// Allocate a new IOSurface large enough to hold `byte_size` bytes
    /// arranged as `shape`. The surface is created as a 1-row,
    /// 1-byte-per-element layout — the GL backend separately allocates
    /// properly-shaped image IOSurfaces (with YUYV/NV12/BGRA FOURCC) via
    /// `crates/image/src/gl/iosurface_import.rs`.
    pub(crate) fn new_with_byte_size(
        shape: &[usize],
        byte_size: usize,
        name: Option<&str>,
    ) -> Result<Self> {
        // Span name follows the project convention `<crate>.<function>`
        // (see `ARCHITECTURE.md § Span naming conventions`). The
        // `memory = "iosurface"` field tags the variant so traces can
        // filter macOS-specific allocations.
        let _span =
            tracing::trace_span!("tensor.alloc", memory = "iosurface", byte_size,).entered();

        // SAFETY: dict is created and consumed within this block; the
        // CFDictionary stays alive across the IOSurfaceCreate call.
        let (dict, ptr) = unsafe {
            let dict = build_props(byte_size.max(1), 1, 1, FOURCC_L008)?;
            let ptr = IOSurfaceCreate(dict);
            (dict, ptr)
        };
        unsafe { CFRelease(dict as *const c_void) };
        let surface = OwnedIoSurface::from_created(ptr)?;
        let identity = identity_from_surface(surface.as_ptr());
        let alloc = unsafe { IOSurfaceGetAllocSize(surface.as_ptr()) };
        let bytes_per_row = unsafe { IOSurfaceGetBytesPerRow(surface.as_ptr()) };

        let name = match name {
            Some(s) => s.to_owned(),
            None => format!("iosurface-{}", uuid::Uuid::new_v4()),
        };

        trace!("IoSurfaceTensor::new: name={name} bytes={alloc} shape={shape:?}",);

        Ok(Self {
            name,
            surface,
            shape: shape.to_vec(),
            _marker: PhantomData,
            identity,
            buf_size: alloc,
            bytes_per_row,
            is_imported: false,
            view_offset: 0,
        })
    }

    /// Allocate an image-formatted IOSurface — proper FourCC + per-pixel
    /// byte count + 2D dimensions, suitable for binding directly via
    /// `EGL_ANGLE_iosurface_client_buffer` on the GL backend.
    ///
    /// Unlike `new_with_byte_size`, the returned IOSurface has the
    /// format ANGLE expects when the GL backend later wraps it in a
    /// pbuffer. Used by `Tensor::image()` on macOS when the caller
    /// requests `TensorMemory::DmaBuf`.
    ///
    /// For planar pixel formats (`PlanarRgb`, `PlanarRgba`) the
    /// IOSurface is allocated as a single-channel float surface sized
    /// `(width, channels * height)` — the channel planes stack
    /// vertically and the byte layout matches the tensor's
    /// `[channels, H, W]` shape.
    pub(crate) fn new_image(
        width: usize,
        height: usize,
        format: PixelFormat,
        dtype: DType,
        shape: &[usize],
        name: Option<&str>,
    ) -> Result<Self> {
        let _span =
            tracing::trace_span!("tensor.alloc", memory = "iosurface", width, height, ?format,)
                .entered();

        let (fourcc, bpe) = crate::iosurface_layout::image_iosurface_layout(format, dtype).ok_or_else(|| {
            Error::NotImplemented(format!(
                "IoSurfaceTensor::new_image: ({format:?}, {dtype:?}) has no IOSurface FourCC mapping"
            ))
        })?;

        // IOSurface geometry per (format, dtype):
        //
        //   * Packed formats (Rgba/Bgra/Yuyv, any supported dtype):
        //     surface dimensions = (width, height).
        //
        //   * PlanarRgb[a] u8: not currently supported (no FourCC).
        //
        //   * PlanarRgb[a] F16: ANGLE only accepts RGBA16F (FourCC
        //     'RGhA') for float IOSurfaces. We pack 4 contiguous f16
        //     elements of the planar `[C, H, W]` byte stream into
        //     each RGBA16F pixel — surface dimensions become
        //     `(W/4, C*H)` via `packed_rgba16f_layout`. The byte
        //     layout is identical to a (nonexistent) R16F `(W, C*H)`
        //     surface and ORT consumes the locked base address as
        //     `&[f16]` with shape `[1, C, H, W]` without
        //     rearrangement. W must be a multiple of 4 for the
        //     packing to align — validated by `packed_rgba16f_layout`.
        let (surface_width, surface_height) = match (format, dtype) {
            (PixelFormat::PlanarRgb | PixelFormat::PlanarRgba, DType::F16) => {
                // Delegate W%4 check and (W/4, C*H) computation to the
                // canonical single source of truth. The only failure mode
                // here is misaligned width (packed_rgba16f_layout returns
                // None); overflow is not possible at these dimensions.
                let layout =
                    packed_rgba16f_layout(format, dtype, width, height).ok_or_else(|| {
                        Error::InvalidShape(format!(
                            "{format:?} F16 IOSurface requires width%4==0 for RGBA16F packing \
                             (got width={width})"
                        ))
                    })?;
                (layout.surface_w, layout.surface_h)
            }
            // Packed RGB u8/i8 rides an RGBA8888 surface at (W*3/4, H) —
            // the same canonical rule as the Android allocation and the GL
            // engine's two-pass packed-RGB render geometry.
            (PixelFormat::Rgb, DType::U8 | DType::I8) => {
                let layout = crate::packed_rgb888_layout(width, height).ok_or_else(|| {
                    Error::InvalidShape(format!(
                        "Rgb u8 IOSurface requires width%4==0 for RGBA8888 packing \
                         (got width={width})"
                    ))
                })?;
                (layout.surface_w, layout.surface_h)
            }
            (PixelFormat::PlanarRgb, _) => {
                let sh = height.checked_mul(3).ok_or_else(|| {
                    Error::InvalidShape(format!("PlanarRgb height overflow (height={height})"))
                })?;
                (width, sh)
            }
            (PixelFormat::PlanarRgba, _) => {
                let sh = height.checked_mul(4).ok_or_else(|| {
                    Error::InvalidShape(format!("PlanarRgba height overflow (height={height})"))
                })?;
                (width, sh)
            }
            // Semi-planar YUV (NV12/NV16/NV24): bind the whole contiguous
            // combined-plane buffer as one R8 texture, sized to the 64-aligned
            // row pitch (see `PixelFormat::semi_planar_surface_dims` for the
            // ANGLE width==pitch rationale).
            (PixelFormat::Nv12 | PixelFormat::Nv16 | PixelFormat::Nv24, _) => format
                .semi_planar_surface_dims(width, height, bpe)
                .ok_or_else(|| {
                    Error::InvalidShape(format!(
                        "{format:?} has no semi-planar surface dims for {width}x{height}"
                    ))
                })?,
            _ => (width, height),
        };

        let dict = unsafe { build_props(surface_width, surface_height, bpe, fourcc) }?;
        let ptr = unsafe { IOSurfaceCreate(dict) };
        unsafe { CFRelease(dict) };
        let surface = OwnedIoSurface::from_created(ptr)?;
        let identity = identity_from_surface(surface.as_ptr());
        let alloc = unsafe { IOSurfaceGetAllocSize(surface.as_ptr()) };
        let bytes_per_row = unsafe { IOSurfaceGetBytesPerRow(surface.as_ptr()) };

        let name = match name {
            Some(s) => s.to_owned(),
            None => format!("iosurface-img-{}", uuid::Uuid::new_v4()),
        };

        trace!(
            "IoSurfaceTensor::new_image: name={name} surface={surface_width}x{surface_height} \
             logical={width}x{height} {format:?}/{dtype:?} fourcc=0x{fourcc:08x} bytes={alloc} \
             bytes_per_row={bytes_per_row}",
        );

        Ok(Self {
            name,
            surface,
            shape: shape.to_vec(),
            _marker: PhantomData,
            identity,
            buf_size: alloc,
            bytes_per_row,
            is_imported: false,
            view_offset: 0,
        })
    }

    /// Wrap an existing IOSurface as a tensor. Used by the GL backend
    /// when importing an externally-allocated surface (e.g. from
    /// VideoToolbox or cross-process `IOSurfaceID` lookup).
    ///
    /// `surface_ref` must be a valid `IOSurfaceRef`. The pointer is
    /// retained for the tensor's lifetime; the external owner keeps its
    /// own reference and must release it independently.
    ///
    /// The type-erased public entry point is [`crate::TensorDyn::from_iosurface`]
    /// (and [`crate::Tensor::from_iosurface`] for the typed wrapper);
    /// most callers should prefer those over calling this inner
    /// constructor directly.
    ///
    /// # Safety
    ///
    /// The caller must ensure `surface_ref` is a valid live
    /// `IOSurfaceRef`. Passing a stale or invalid pointer is UB.
    ///
    /// The shape footprint
    /// (`shape.iter().product::<usize>() * std::mem::size_of::<T>()`) is
    /// validated against the IOSurface's allocated byte size
    /// (`IOSurfaceGetAllocSize`) and the constructor returns
    /// `Err(InvalidShape)` if it does not fit. This catches accidental
    /// mismatches that would otherwise cause out-of-bounds reads/writes
    /// in [`crate::Tensor::map`]; it does not relax the pointer-validity
    /// requirement above.
    pub unsafe fn from_surface(
        surface_ref: *mut c_void,
        shape: &[usize],
        name: Option<&str>,
    ) -> Result<Self> {
        unsafe {
            let surface = OwnedIoSurface::from_external(surface_ref)?;
            let identity = identity_from_surface(surface.as_ptr());
            let alloc = IOSurfaceGetAllocSize(surface.as_ptr());
            let bytes_per_row = IOSurfaceGetBytesPerRow(surface.as_ptr());

            let elem_size = std::mem::size_of::<T>();
            let elems: usize = shape.iter().product();
            let requested = elems.checked_mul(elem_size).ok_or_else(|| {
            Error::InvalidShape(format!(
                "from_surface: shape footprint overflows usize (shape={shape:?}, sizeof T={elem_size})",
            ))
        })?;
            if requested > alloc {
                return Err(Error::InvalidShape(format!(
                    "from_surface: shape requires {requested} bytes but IOSurface only \
                 has {alloc} (shape={shape:?}, sizeof T={elem_size})",
                )));
            }

            let name = match name {
                Some(s) => s.to_owned(),
                None => format!("iosurface-imported-{}", uuid::Uuid::new_v4()),
            };
            Ok(Self {
                name,
                surface,
                shape: shape.to_vec(),
                _marker: PhantomData,
                identity,
                buf_size: alloc,
                bytes_per_row,
                is_imported: true,
                view_offset: 0,
            })
        }
    }

    /// Row pitch in bytes as reported by `IOSurfaceGetBytesPerRow` (64-byte
    /// aligned). For image-formatted surfaces this is the authoritative row
    /// stride; CPU consumers must iterate rows by this value, not by
    /// `width × bytes_per_pixel`.
    pub(crate) fn bytes_per_row(&self) -> usize {
        self.bytes_per_row
    }

    /// Physical IOSurface dimensions in *texels* (`IOSurfaceGetWidth` /
    /// `IOSurfaceGetHeight`), independent of the tensor's current logical shape.
    ///
    /// A reused pool surface keeps these fixed for its whole life while
    /// `configure_image` changes the logical frame shape per decode. The GL
    /// backend binds the EGL pbuffer at these physical dims so one cached
    /// pbuffer serves every frame, and `texelFetch(col, row)` resolves to memory
    /// `row * bytes_per_row + col` (the row pitch is carried by the surface, not
    /// the declared texel width) — matching the codec's fixed-grid byte layout.
    pub(crate) fn physical_surface_dims(&self) -> (usize, usize) {
        let w = unsafe { IOSurfaceGetWidth(self.surface.as_ptr()) };
        let h = unsafe { IOSurfaceGetHeight(self.surface.as_ptr()) };
        (w, h)
    }

    /// Row pitch to honour as an *image* stride when a tensor is reconfigured
    /// to a smaller image (`Tensor::configure_image`), or `None` for a generic
    /// byte-bag surface.
    ///
    /// A byte-bag (`new_with_byte_size`) is a single `height == 1` row whose
    /// `bytes_per_row` equals the entire allocation — meaningless as a per-row
    /// image pitch. Adopting it would set a row stride spanning the whole buffer
    /// and blow up the strided map's size check. Only genuine 2D image-formatted
    /// surfaces (`new_image`, height > 1) carry a real row pitch to preserve.
    pub(crate) fn image_backing_row_stride(&self) -> Option<usize> {
        let (_w, h) = self.physical_surface_dims();
        (h > 1).then_some(self.bytes_per_row)
    }

    /// Lock and map exposing `byte_size` bytes via `as_slice()` for strided
    /// row iteration. The caller (`Tensor::map`) validates
    /// `byte_size <= buf_size` first. The IOSurface lock yields the full
    /// surface base address, so the strided view is genuinely zero-copy — no
    /// staging buffer, just a wider slice over the same locked allocation.
    pub(crate) fn map_with_byte_size<'a>(
        &self,
        byte_size: usize,
        access: crate::CpuAccess,
    ) -> Result<crate::view::HostView<'a, T>>
    where
        T: 'a,
    {
        self.map_inner(Some(byte_size), access)
    }

    /// Raw `IOSurfaceID` for cross-process sharing or GL backend import.
    pub fn surface_id(&self) -> u32 {
        unsafe { IOSurfaceGetID(self.surface.as_ptr()) }
    }

    /// Raw `IOSurfaceRef` for the GL backend to pass to
    /// `eglCreatePbufferFromClientBuffer(EGL_IOSURFACE_ANGLE, ...)`.
    pub fn surface_ref(&self) -> *mut c_void {
        self.surface.as_ptr()
    }
}

// ---------------------------------------------------------------------------
// Tensor<T>::iosurface_ref accessor — macOS-only.
//
// The GL backend (image crate) calls this when importing an
// IOSurface-backed tensor as an EGL pbuffer. Returns None for tensors
// backed by SHM/Mem/Pbo since they have no associated IOSurface.
// ---------------------------------------------------------------------------

impl<T> crate::Tensor<T>
where
    T: Num + Clone + fmt::Debug + Send + Sync,
{
    /// Borrow the underlying `IOSurfaceRef` for this tensor (macOS only).
    ///
    /// Returns `Some(ptr)` when the tensor is backed by IOSurface (i.e.
    /// `TensorMemory::DmaBuf` on macOS), `None` otherwise. The pointer is
    /// borrowed — its lifetime is tied to the tensor.
    pub fn iosurface_ref(&self) -> Option<*mut c_void> {
        match &self.storage {
            crate::TensorStorage::Dma(io_tensor) => Some(io_tensor.surface_ref()),
            _ => None,
        }
    }

    /// Return the IOSurfaceID for cross-process IOSurface lookup
    /// (macOS only). Returns `None` when the tensor is not
    /// IOSurface-backed.
    ///
    /// The ID is stable for the lifetime of the IOSurface and can be
    /// passed across process boundaries; the receiver recovers the
    /// `IOSurfaceRef` via `IOSurfaceLookup(id)`.
    pub fn iosurface_id(&self) -> Option<u32> {
        match &self.storage {
            crate::TensorStorage::Dma(io_tensor) => Some(io_tensor.surface_id()),
            _ => None,
        }
    }

    /// Physical IOSurface dimensions in texels (`IOSurfaceGetWidth` /
    /// `IOSurfaceGetHeight`), independent of the logical shape. `None` when not
    /// IOSurface-backed.
    ///
    /// The GL backend binds the EGL pbuffer at these dims so one cached pbuffer
    /// serves every frame a reused pool surface holds; `texelFetch` then
    /// resolves to `row * bytesPerRow + col` against the surface's real pitch.
    pub fn iosurface_physical_dims(&self) -> Option<(usize, usize)> {
        match &self.storage {
            crate::TensorStorage::Dma(io_tensor) => Some(io_tensor.physical_surface_dims()),
            _ => None,
        }
    }

    /// Wrap an externally-allocated IOSurface as a tensor (macOS only).
    ///
    /// Used to import IOSurfaces from VideoToolbox, AVFoundation, or
    /// other producers, and to recover a tensor from an IOSurfaceID
    /// received over a Mach port or XPC connection. The surface is
    /// retained for the tensor's lifetime; the external owner keeps
    /// its own reference and must release it independently.
    ///
    /// # Safety
    ///
    /// `surface_ref` must be a valid live `IOSurfaceRef`. Passing a
    /// stale or invalid pointer is UB.
    ///
    /// HAL validates that
    /// `shape.iter().product::<usize>() * std::mem::size_of::<T>()` fits
    /// within the IOSurface's allocated byte size
    /// (`IOSurfaceGetAllocSize`) and returns `Err(InvalidShape)`
    /// otherwise. The pointer-validity requirement above is the
    /// caller's responsibility.
    pub unsafe fn from_iosurface(
        surface_ref: *mut c_void,
        shape: &[usize],
        name: Option<&str>,
    ) -> Result<Self>
    where
        T: num_traits::Num,
    {
        let inner = unsafe { IoSurfaceTensor::<T>::from_surface(surface_ref, shape, name)? };
        Ok(crate::Tensor::wrap(crate::TensorStorage::Dma(inner)))
    }
}

// ---------------------------------------------------------------------------
// IoSurfaceMap — locked-for-CPU view.
// ---------------------------------------------------------------------------

// ---------------------------------------------------------------------------
// CFDictionary builder for IOSurfaceCreate
// ---------------------------------------------------------------------------

/// `L008` (kCVPixelFormatType_OneComponent8) — single-channel 8-bit
/// layout used for raw-byte allocations from
/// `IoSurfaceTensor::new_with_byte_size`.
const FOURCC_L008: u32 = u32::from_be_bytes(*b"L008");

unsafe fn build_props(
    width: usize,
    height: usize,
    bytes_per_element: usize,
    fourcc: u32,
) -> Result<CFDictionaryRef> {
    unsafe {
        // Checked arithmetic (mirrors the image crate's `build_image_props`): an
        // overflowing pitch or allocation size would describe an under-sized
        // IOSurface that the GL import then treats as a valid buffer — a memory
        // hazard. Fail loudly instead of wrapping.
        let bytes_per_row = width
            .checked_mul(bytes_per_element)
            .and_then(|b| b.checked_add(63))
            .map(|b| b & !63)
            .ok_or_else(|| {
                Error::InvalidShape(format!(
                    "IOSurface bytes-per-row overflow (width={width}, bpe={bytes_per_element})"
                ))
            })?;
        let alloc_size = bytes_per_row.checked_mul(height).ok_or_else(|| {
            Error::InvalidShape(format!(
            "IOSurface allocation size overflow (bytes_per_row={bytes_per_row}, height={height})"
        ))
        })?;

        let dict = CFDictionaryCreateMutable(
            std::ptr::null(),
            0,
            &kCFTypeDictionaryKeyCallBacks,
            &kCFTypeDictionaryValueCallBacks,
        );
        if dict.is_null() {
            return Err(Error::IoError(std::io::Error::other(
                "CFDictionaryCreateMutable returned null",
            )));
        }

        let set_num = |key: &str, value: i64| -> Result<()> {
            let key_c = std::ffi::CString::new(key)
                .map_err(|e| Error::InvalidArgument(format!("CString: {e}")))?;
            let key_cf = CFStringCreateWithCString(
                std::ptr::null(),
                key_c.as_ptr(),
                K_CF_STRING_ENCODING_UTF8,
            );
            if key_cf.is_null() {
                return Err(Error::IoError(std::io::Error::other(
                    "CFStringCreateWithCString returned null",
                )));
            }
            let value_cf = CFNumberCreate(
                std::ptr::null(),
                K_CF_NUMBER_LONG_TYPE,
                &value as *const i64 as *const c_void,
            );
            if value_cf.is_null() {
                CFRelease(key_cf as *const c_void);
                return Err(Error::IoError(std::io::Error::other(
                    "CFNumberCreate returned null",
                )));
            }
            CFDictionarySetValue(dict, key_cf as *const c_void, value_cf as *const c_void);
            CFRelease(key_cf as *const c_void);
            CFRelease(value_cf as *const c_void);
            Ok(())
        };

        let result = (|| -> Result<()> {
            set_num("IOSurfaceWidth", width as i64)?;
            set_num("IOSurfaceHeight", height as i64)?;
            set_num("IOSurfaceBytesPerElement", bytes_per_element as i64)?;
            set_num("IOSurfacePixelFormat", fourcc as i64)?;
            set_num("IOSurfaceBytesPerRow", bytes_per_row as i64)?;
            set_num("IOSurfaceAllocSize", alloc_size as i64)?;
            Ok(())
        })();

        if let Err(e) = result {
            CFRelease(dict as *const c_void);
            return Err(e);
        }
        Ok(dict)
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::TensorMapTrait;

    #[test]
    fn alloc_map_write_read_roundtrip() {
        let t = IoSurfaceTensor::<u8>::new(&[256], None).expect("alloc");
        assert!(t.buf_size >= 256, "buf_size should accommodate shape");
        assert_eq!(t.memory(), TensorMemory::DmaBuf);

        // Write via map
        {
            let mut m = t.map().expect("map");
            let slice = m.as_mut_slice();
            assert!(slice.len() >= 256);
            for (i, b) in slice.iter_mut().take(256).enumerate() {
                *b = (i & 0xff) as u8;
            }
        }
        // Read back via fresh map
        {
            let m = t.map().expect("remap");
            let slice = m.as_slice();
            for (i, b) in slice.iter().take(256).enumerate() {
                assert_eq!(*b, (i & 0xff) as u8, "byte {i} mismatch");
            }
        }
    }

    #[test]
    fn wrap_clone_drop_moves_cf_retain_count_by_one() {
        // IOSurfaceCreate returns a +1 ref that from_created takes ownership of.
        // Arc-cloning OwnedIoSurface must not CFRetain. from_external must +1,
        // and dropping that handle must -1. Silence here was the G20 deferral.
        let t = IoSurfaceTensor::<u8>::new(&[64], None).expect("alloc");
        let ptr = t.surface.as_ptr() as *const c_void;
        let base = unsafe { CFGetRetainCount(ptr) };
        assert!(base >= 1, "create must leave a live retain, got {base}");

        let clone = t.surface.clone();
        assert_eq!(
            unsafe { CFGetRetainCount(ptr) },
            base,
            "Arc clone of OwnedIoSurface must not CFRetain"
        );
        drop(clone);
        assert_eq!(unsafe { CFGetRetainCount(ptr) }, base);

        let extra = OwnedIoSurface::from_external(t.surface.as_ptr()).expect("retain");
        assert_eq!(
            unsafe { CFGetRetainCount(ptr) },
            base + 1,
            "from_external must CFRetain"
        );
        drop(extra);
        assert_eq!(
            unsafe { CFGetRetainCount(ptr) },
            base,
            "dropping from_external must CFRelease"
        );
    }

    #[test]
    fn image_surface_strided_map_honours_bytes_per_row() {
        use crate::Tensor;

        // Packed RGBA U8 at width 17: natural row = 68 B, which IOSurface pads
        // up to a 64-aligned `bytes_per_row` (128 B). Previously `image()`
        // rejected this (forcing an SHM fallback); now it allocates a padded
        // IOSurface and records the stride, so CPU access is correct + zero-copy.
        let h = 3usize;
        let w = 17usize;
        let t = Tensor::<u8>::image(
            w,
            h,
            PixelFormat::Rgba,
            Some(TensorMemory::DmaBuf),
            crate::CpuAccess::ReadWrite,
        )
        .expect("non-aligned packed RGBA should allocate a padded IOSurface");

        let stride = t.effective_row_stride().expect("stride");
        assert!(stride >= w * 4, "stride {stride} >= natural {}", w * 4);
        assert_eq!(stride % 64, 0, "IOSurface pads bytes_per_row to 64");
        assert!(stride > w * 4, "width 17 RGBA must be padded (68 -> 128)");
        assert_eq!(t.width(), Some(w));
        assert_eq!(t.height(), Some(h));

        // Write a distinct value per logical pixel, iterating rows by `stride`.
        {
            let mut m = t.map().expect("strided IOSurface map");
            let buf = m.as_mut_slice();
            assert_eq!(buf.len(), stride * h, "map exposes the full padded surface");
            for row in 0..h {
                for col in 0..w * 4 {
                    buf[row * stride + col] = (row * 37 + col) as u8;
                }
            }
        }
        // Read back via a fresh lock and verify the padded layout round-trips.
        {
            let m = t.map().expect("remap");
            let buf = m.as_slice();
            for row in 0..h {
                for col in 0..w * 4 {
                    assert_eq!(
                        buf[row * stride + col],
                        (row * 37 + col) as u8,
                        "pixel byte ({row},{col}) mismatch"
                    );
                }
            }
        }
    }

    #[test]
    fn copy_to_flat_compacts_padded_rows() {
        use crate::{Tensor, TensorDyn};

        // Width 17 RGBA u8: natural row = 68 B, IOSurface pads to 128 B —
        // the recorded-stride case copy_to_flat exists for. Write a
        // distinct byte per logical pixel via the strided map, then verify
        // the flat copy is tight and padding-free.
        let (w, h) = (17usize, 3usize);
        let t = Tensor::<u8>::image(
            w,
            h,
            PixelFormat::Rgba,
            Some(TensorMemory::DmaBuf),
            crate::CpuAccess::ReadWrite,
        )
        .expect("padded IOSurface alloc");
        let stride = t.effective_row_stride().expect("stride");
        assert!(stride > w * 4, "test requires a padded stride");
        {
            let mut m = t.map().expect("map");
            let buf = m.as_mut_slice();
            for row in 0..h {
                for col in 0..w * 4 {
                    buf[row * stride + col] = (row * 91 + col) as u8;
                }
            }
        }
        let mut flat = vec![0u8; h * w * 4];
        t.copy_to_flat(&mut flat).expect("copy_to_flat");
        for row in 0..h {
            for col in 0..w * 4 {
                assert_eq!(
                    flat[row * w * 4 + col],
                    (row * 91 + col) as u8,
                    "flat byte ({row},{col})"
                );
            }
        }

        // Wrong destination size errors instead of truncating.
        let mut short = vec![0u8; h * w * 4 - 1];
        assert!(t.copy_to_flat(&mut short).is_err());

        // Tight tensors (no recorded stride) degenerate to one memcpy —
        // exercised through the TensorDyn dispatch layer.
        let tight = TensorDyn::image(
            64,
            4,
            PixelFormat::Rgba,
            DType::U8,
            Some(TensorMemory::Mem),
            crate::CpuAccess::ReadWrite,
        )
        .expect("tight Mem alloc");
        {
            let tu8 = tight.as_u8().unwrap();
            let mut m = tu8.map().expect("map");
            for (i, b) in m.as_mut_slice().iter_mut().enumerate() {
                *b = (i % 251) as u8;
            }
        }
        let mut flat2 = vec![0u8; 64 * 4 * 4];
        tight.copy_to_flat(&mut flat2).expect("tight copy_to_flat");
        for (i, b) in flat2.iter().enumerate() {
            assert_eq!(*b, (i % 251) as u8, "tight byte {i}");
        }
    }

    #[test]
    fn explicit_dma_unmapped_image_format_errors() {
        use crate::Tensor;

        // Explicit-Dma contract: `Some(TensorMemory::DmaBuf)` for an image whose
        // (format, dtype) has no IOSurface FourCC mapping must error loudly —
        // NOT silently allocate a generic 'L008' byte-bag that every GL
        // import later rejects with EGL_BAD_ATTRIBUTE. Width 64 keeps the
        // natural pitch 64-aligned so this exercises the mapping check, not
        // the alignment guard.
        for (name, result) in [
            (
                "PlanarRgb u8",
                Tensor::<u8>::image(
                    64,
                    8,
                    PixelFormat::PlanarRgb,
                    Some(TensorMemory::DmaBuf),
                    crate::CpuAccess::ReadWrite,
                )
                .map(drop),
            ),
            (
                "Rgb f32",
                Tensor::<f32>::image(
                    64,
                    8,
                    PixelFormat::Rgb,
                    Some(TensorMemory::DmaBuf),
                    crate::CpuAccess::ReadWrite,
                )
                .map(drop),
            ),
        ] {
            match result {
                Err(crate::Error::InvalidArgument(msg)) => {
                    assert!(
                        msg.contains("no zero-copy IOSurface mapping"),
                        "{name}: error must name the missing mapping: {msg}"
                    );
                }
                other => panic!("{name}: expected InvalidArgument, got {other:?}"),
            }
        }

        // The designed 'L008' semi-planar arm is a mapping, not a byte-bag:
        // NV12 u8 with explicit Dma must still allocate (the R8 plane the
        // YUV shaders sample) — the contract fix must not break it.
        let nv12 = Tensor::<u8>::image(
            64,
            8,
            PixelFormat::Nv12,
            Some(TensorMemory::DmaBuf),
            crate::CpuAccess::ReadWrite,
        )
        .expect("NV12 u8 keeps its designed L008 IOSurface mapping");
        assert_eq!(nv12.memory(), TensorMemory::DmaBuf);
    }

    #[test]
    fn surface_id_is_nonzero() {
        let t = IoSurfaceTensor::<u8>::new(&[64], None).expect("alloc");
        assert!(t.surface_id() != 0, "IOSurface IDs should be nonzero");
    }

    #[test]
    fn shape_reshape_roundtrip() {
        let mut t = IoSurfaceTensor::<u8>::new(&[16, 16], None).expect("alloc");
        assert_eq!(t.shape(), &[16, 16]);
        t.reshape(&[256]).expect("flatten");
        assert_eq!(t.shape(), &[256]);
        // Element count mismatch rejected
        assert!(t.reshape(&[100]).is_err());
    }

    #[test]
    fn fourcc_layout_u8_packed_unchanged() {
        // U8 packed formats keep the legacy mappings (regression
        // guard for the refactor that added dtype to the lookup).
        assert_eq!(
            crate::iosurface_layout::image_iosurface_layout(PixelFormat::Rgba, DType::U8),
            Some((u32::from_be_bytes(*b"RGBA"), 4))
        );
        assert_eq!(
            crate::iosurface_layout::image_iosurface_layout(PixelFormat::Bgra, DType::U8),
            Some((u32::from_be_bytes(*b"BGRA"), 4))
        );
        assert_eq!(
            crate::iosurface_layout::image_iosurface_layout(PixelFormat::Yuyv, DType::U8),
            Some((u32::from_be_bytes(*b"2C08"), 2))
        );
        // Packed RGB u8 rides an RGBA8888 surface at (W*3/4, H) — the
        // format is RGBA even though the pixel format is Rgb (matches
        // the Android AHardwareBuffer table).
        assert_eq!(
            crate::iosurface_layout::image_iosurface_layout(PixelFormat::Rgb, DType::U8),
            Some((u32::from_be_bytes(*b"RGBA"), 4))
        );
    }

    #[test]
    fn fourcc_layout_f16_packed_rgba16f() {
        // ANGLE's iosurface_client_buffer extension supports exactly
        // one float (type, internal_format) pair: (GL_HALF_FLOAT,
        // GL_RGBA) = RGBA16F, FourCC 'RGhA'. All HAL F16 IOSurface
        // destinations (packed Rgba or planar) use this mapping.
        let expected = (u32::from_be_bytes(*b"RGhA"), 8);
        assert_eq!(
            crate::iosurface_layout::image_iosurface_layout(PixelFormat::Rgba, DType::F16),
            Some(expected)
        );
        assert_eq!(
            crate::iosurface_layout::image_iosurface_layout(PixelFormat::PlanarRgb, DType::F16),
            Some(expected)
        );
        assert_eq!(
            crate::iosurface_layout::image_iosurface_layout(PixelFormat::PlanarRgba, DType::F16),
            Some(expected)
        );
    }

    #[test]
    fn fourcc_layout_unsupported_combinations_return_none() {
        // PlanarRgb / PlanarRgba u8 not supported on the IOSurface
        // path — those tensors stay on SHM/Mem storage.
        assert_eq!(
            crate::iosurface_layout::image_iosurface_layout(PixelFormat::PlanarRgb, DType::U8),
            None
        );
        assert_eq!(
            crate::iosurface_layout::image_iosurface_layout(PixelFormat::PlanarRgba, DType::U8),
            None
        );
        // F32 isn't accepted by ANGLE's IOSurface extension at all —
        // no GL_FLOAT entry on the allowlist. Any F32 combination
        // must return None so consumers fall back to staging.
        assert_eq!(
            crate::iosurface_layout::image_iosurface_layout(PixelFormat::Rgba, DType::F32),
            None
        );
        assert_eq!(
            crate::iosurface_layout::image_iosurface_layout(PixelFormat::PlanarRgb, DType::F32),
            None
        );
        // NV12/NV16/NV24/GREY (u8) now map to 'L008' (R8) so the GPU can sample
        // the contiguous semi-planar buffer as a single-channel texture.
        assert_eq!(
            crate::iosurface_layout::image_iosurface_layout(PixelFormat::Nv12, DType::U8),
            Some((u32::from_be_bytes(*b"L008"), 1))
        );
        // Float for YUYV / Grey isn't a meaningful combination.
        assert_eq!(
            crate::iosurface_layout::image_iosurface_layout(PixelFormat::Yuyv, DType::F16),
            None
        );
        assert_eq!(
            crate::iosurface_layout::image_iosurface_layout(PixelFormat::Grey, DType::F16),
            None
        );
    }

    #[test]
    fn new_image_planar_f16_packs_into_rgba16f() {
        // PlanarRgb F16: logical 64×32 image gets a packed RGBA16F
        // IOSurface sized (64/4, 3*32) = (16, 96). 8 B/pixel,
        // bytes_per_row rounded to 64-byte alignment (16*8 = 128,
        // already aligned) = 128, * 96 rows = 12288 bytes total. The
        // byte payload exactly matches an [3, 32, 64] f16 tensor
        // (3*32*64*2 = 12288 bytes).
        let shape = [3, 32, 64];
        let t = IoSurfaceTensor::<half::f16>::new_image(
            64,
            32,
            PixelFormat::PlanarRgb,
            DType::F16,
            &shape,
            None,
        )
        .expect("PlanarRgb F16 IOSurface allocation");
        assert!(t.buf_size >= 3 * 32 * 64 * 2);
    }

    #[test]
    fn new_image_planar_f16_rejects_misaligned_width() {
        // W=63 isn't divisible by 4 — packing would mis-align the
        // last column. HAL must reject at allocation time rather than
        // silently truncate.
        let shape = [3, 32, 63];
        let err = IoSurfaceTensor::<half::f16>::new_image(
            63,
            32,
            PixelFormat::PlanarRgb,
            DType::F16,
            &shape,
            None,
        )
        .expect_err("misaligned width must be rejected");
        match err {
            Error::InvalidShape(msg) => assert!(
                msg.contains("width%4==0") || msg.contains("RGBA16F"),
                "unexpected message: {msg}"
            ),
            other => panic!("expected InvalidShape, got {other:?}"),
        }
    }

    #[test]
    fn new_image_packed_rgba_f16_alloc_size_matches_dtype() {
        // Packed Rgba F16 at 64×32 → 64 pixels × 8 bytes/pixel = 512 B/row
        // (8-byte aligned, padded up to 64-byte stride), × 32 rows
        // ≥ 16384 bytes. (Equals 32*64*8 = 16384 bytes.)
        let shape = [32, 64, 4];
        let t = IoSurfaceTensor::<half::f16>::new_image(
            64,
            32,
            PixelFormat::Rgba,
            DType::F16,
            &shape,
            None,
        )
        .expect("Rgba F16 IOSurface allocation");
        assert!(t.buf_size >= 32 * 64 * 8);
    }

    #[test]
    fn from_surface_rejects_shape_overflowing_alloc() {
        // Allocate a small backing surface and try to import it under a
        // shape whose footprint is much larger than the allocation.
        let src = IoSurfaceTensor::<u8>::new(&[64], None).expect("alloc");
        let alloc = src.buf_size;
        let surface_ref = src.surface.as_ptr();

        // u32 element type: requested bytes = (alloc + 1) * 4 ≫ alloc.
        let bad_shape = [alloc + 1];
        let err = unsafe { IoSurfaceTensor::<u32>::from_surface(surface_ref, &bad_shape, None) }
            .expect_err("oversized shape must be rejected");
        match err {
            Error::InvalidShape(msg) => assert!(
                msg.contains("IOSurface only has"),
                "unexpected message: {msg}"
            ),
            other => panic!("expected InvalidShape, got {other:?}"),
        }

        // Sanity check: the same surface accepts a shape that does fit.
        let ok_shape = [alloc / std::mem::size_of::<u32>()];
        unsafe { IoSurfaceTensor::<u32>::from_surface(surface_ref, &ok_shape, None) }
            .expect("fitting shape should succeed");
    }

    /// A `subview` of an IOSurface shares the surface + identity and reads its
    /// own window through the CPU map — the macOS half of the decoder sub-view
    /// fix (previously this errored with "subview only supported for Mem, Dma,
    /// and Shm tensors" because the `Dma` arm was Linux-gated).
    #[test]
    fn subview_iosurface_shares_identity_and_offsets_map() {
        use crate::{Tensor, TensorTrait};

        // 256-byte IOSurface filled with a ramp so each byte equals its index.
        let parent = Tensor::<u8>::new(&[256], Some(TensorMemory::DmaBuf), None).expect("alloc");
        assert_eq!(parent.memory(), TensorMemory::DmaBuf);
        {
            let mut m = parent.map().expect("map parent");
            for (i, b) in m.as_mut_slice().iter_mut().take(256).enumerate() {
                *b = (i & 0xff) as u8;
            }
        }

        // A 64-byte window starting at offset 64 must alias the same buffer.
        let view = parent
            .subview(64, &[64])
            .expect("iosurface subview must succeed");
        assert_eq!(
            view.buffer_identity().id(),
            parent.buffer_identity().id(),
            "subview shares the parent BufferIdentity (one GL import)"
        );

        // The window reads bytes [64, 128) — offset honoured by the CPU map.
        let m = view.map().expect("map iosurface subview");
        let s = m.as_slice();
        assert_eq!(s.len(), 64, "window exposes exactly its logical length");
        for (i, b) in s.iter().enumerate() {
            assert_eq!(
                *b,
                ((i + 64) & 0xff) as u8,
                "view byte {i} must be parent[{}]",
                i + 64
            );
        }

        // Writes through the window land in the parent buffer (zero-copy alias).
        drop(m);
        {
            let mut mw = view.map().expect("remap for write");
            mw.as_mut_slice()[0] = 0xAB;
        }
        let mp = parent.map().expect("remap parent");
        assert_eq!(
            mp.as_slice()[64],
            0xAB,
            "write through view is visible in parent"
        );
    }

    /// Pins the bound `map_inner` already enforces, which issue #161 made
    /// load-bearing: before it, `view_offset` could only come from `view()`
    /// under that function's own bounds check, and now `set_plane_offset`
    /// writes a descriptor's restored offset -- untrusted cross-package input
    /// -- straight into it.
    ///
    /// Nothing here is new behaviour; the point is that removing the
    /// `view_offset + exposed <= buf_size` check in `map_inner` would now be
    /// reachable from a descriptor rather than only from a bug in `view()`.
    /// Two things would go wrong. `scoped_pin` offsets the locked base
    /// address by `view_offset`, which leaves the allocation entirely -- and
    /// forming that pointer is undefined behaviour before anything reads it.
    /// And an offset merely *close* to the end yields a map shorter than the
    /// image while the tensor still reports its full shape, which the GL
    /// upload path reads `width x height` from through a raw pointer that
    /// cannot see a slice's length.
    ///
    /// `D3d11TextureTensor` had no equivalent of this check; see
    /// `d3d11_map_refuses_a_plane_offset_past_the_backing`, which this test's
    /// bounds now match.
    #[test]
    fn iosurface_map_refuses_a_plane_offset_that_cannot_hold_the_image() {
        use crate::{DType, Tensor, TensorDyn, TensorTrait};

        const PARENT: usize = 256;
        const WINDOW: usize = 64;

        let parent = Tensor::<u8>::new(&[PARENT], Some(TensorMemory::DmaBuf), None).expect("alloc");
        assert_eq!(parent.memory(), TensorMemory::DmaBuf);
        let parent_dyn = TensorDyn::from(parent);
        let id = parent_dyn
            .iosurface_id()
            .expect("parent is IOSurface-backed");
        // The surface's own allocation, which IOSurface may round up past the
        // 256 bytes asked for -- the bound is the real one, not the request.
        let capacity = parent_dyn
            .map_bytes(crate::CpuAccess::Read)
            .expect("map parent")
            .as_slice()
            .len();

        let mut rebuilt = TensorDyn::from_iosurface_id(id, &[WINDOW], DType::U8, None)
            .expect("reconstruct at the view's shape");

        // A window that still holds its whole 64 bytes is fine, including the
        // one that ends exactly at the surface's end.
        rebuilt.set_plane_offset(capacity - WINDOW);
        assert_eq!(
            rebuilt
                .map_bytes(crate::CpuAccess::Read)
                .expect("the last window that fits")
                .as_slice()
                .len(),
            WINDOW,
            "a window ending exactly at the surface's end must still map"
        );

        // One byte further and the image no longer fits. Refused, rather than
        // handed back one byte short.
        rebuilt.set_plane_offset(capacity - WINDOW + 1);
        let err = rebuilt
            .map_bytes(crate::CpuAccess::Read)
            .expect_err("a window one byte short of its image");
        assert!(
            matches!(err, Error::InsufficientCapacity { .. }),
            "expected InsufficientCapacity, got {err}"
        );

        // The degenerate one-past-the-end offset: a legal pointer, an empty
        // window, and a tensor that still calls itself 64 bytes wide.
        rebuilt.set_plane_offset(capacity);
        assert!(
            rebuilt.map_bytes(crate::CpuAccess::Read).is_err(),
            "an empty window for a non-empty tensor must not map"
        );

        // Far past the surface, and a value chosen to overflow if the bound
        // were computed with wrapping arithmetic.
        rebuilt.set_plane_offset(usize::MAX);
        assert!(
            rebuilt.map_bytes(crate::CpuAccess::Read).is_err(),
            "usize::MAX must not wrap into range"
        );
    }

    /// Restoring a plane offset onto a *reconstructed* IOSurface tensor must
    /// move where `map()` starts. Regression test for issue #161.
    ///
    /// `TensorDesc` has no field for the plane offset, so every path that
    /// rebuilds a tensor from a descriptor puts the offset back by calling
    /// `Tensor::set_plane_offset` — `edgefirst-python-common`'s
    /// `interop::apply_plane_offset` is the caller that matters. That call was
    /// a silent no-op on this backing: `set_plane_offset`'s `Dma` arm was
    /// `cfg(target_os = "linux")`, and because `TensorStorage::Dma` is a
    /// cfg-multiplexed *name* rather than one type, macOS did not fail to
    /// compile — it fell through to the catch-all. A reconstructed `view()`
    /// therefore addressed the parent surface's origin, silently, with no
    /// error to follow.
    ///
    /// Distinct from `subview_iosurface_shares_identity_and_offsets_map`
    /// above, which covers the *fresh* view path: `IoSurfaceTensor::view` sets
    /// its own `view_offset` and always did. Only restoring an offset onto an
    /// already-built tensor was broken — which is exactly why a freshly
    /// created view was correct on every platform and only the descriptor
    /// round trip was wrong.
    ///
    /// The reconstruction is spelled with `TensorDyn::from_iosurface_id`
    /// because that is the same `lookup_by_id` + `from_iosurface` pair that
    /// `import_storage`'s `kind::IOSURFACE` arm runs, without needing the
    /// Python capsule layer to reach it.
    #[test]
    fn set_plane_offset_moves_the_iosurface_map_window() {
        use crate::{DType, Tensor, TensorDyn, TensorTrait};

        const PARENT: usize = 256;
        const OFFSET: usize = 64;
        const WINDOW: usize = 64;

        // Ramp the parent surface so byte i holds i: a window that lands at
        // the wrong origin cannot coincidentally match the expected bytes.
        let parent = Tensor::<u8>::new(&[PARENT], Some(TensorMemory::DmaBuf), None).expect("alloc");
        assert_eq!(parent.memory(), TensorMemory::DmaBuf);
        {
            let mut m = parent.map().expect("map parent");
            for (i, b) in m.as_mut_slice().iter_mut().enumerate() {
                *b = (i & 0xff) as u8;
            }
        }
        let parent_dyn = TensorDyn::from(parent);
        let id = parent_dyn
            .iosurface_id()
            .expect("parent is IOSurface-backed");

        // Reopen the *whole* surface at the sub-region's shape, as an import
        // does: the handle names the parent, so this lands at its origin.
        let mut rebuilt = TensorDyn::from_iosurface_id(id, &[WINDOW], DType::U8, None)
            .expect("reconstruct at the view's shape");
        {
            let m = rebuilt
                .map_bytes(crate::CpuAccess::Read)
                .expect("map rebuilt before the offset");
            assert_eq!(
                m.as_slice()[0],
                0,
                "precondition: a bare import starts at the parent's origin"
            );
        }

        // The restore under test.
        rebuilt.set_plane_offset(OFFSET);
        assert_eq!(
            rebuilt.plane_offset(),
            Some(OFFSET),
            "the wrapper field records the offset on every backing"
        );

        let m = rebuilt
            .map_bytes(crate::CpuAccess::Read)
            .expect("map rebuilt after the offset");
        let s = m.as_slice();
        assert_eq!(s.len(), WINDOW, "the window exposes its logical length");
        assert_ne!(
            s[0], 0,
            "map() still starts at the parent's origin — set_plane_offset was \
             a no-op on IOSurface storage (issue #161)"
        );
        for (i, b) in s.iter().enumerate() {
            assert_eq!(
                *b,
                ((i + OFFSET) & 0xff) as u8,
                "window byte {i} must be parent[{}]",
                i + OFFSET
            );
        }
    }

    /// A nested `subview` must not compound its offset now that
    /// `set_plane_offset` writes through to IOSurface storage.
    ///
    /// The double-apply guard for the fix above, and the reason it needed
    /// checking rather than assuming: `Tensor::subview` sets the offset
    /// *twice* by two different routes. `TensorStorage::view` computes
    /// `view_offset + offset_bytes` inside `IoSurfaceTensor::view`, and then
    /// `subview` calls `set_plane_offset(plane_offset + offset_bytes)` on the
    /// result. Those are the same number only while the wrapper field and the
    /// storage field stay in sync — which is what the new arm makes true, and
    /// what an unguarded restore got wrong on `MEM` in the DMA-BUF half of
    /// this fix (PR #160). Two levels, because a single level cannot tell an
    /// idempotent write apart from one that compounds from zero.
    #[test]
    fn nested_iosurface_subviews_do_not_compound_their_plane_offset() {
        use crate::{Tensor, TensorTrait};

        let parent = Tensor::<u8>::new(&[256], Some(TensorMemory::DmaBuf), None).expect("alloc");
        {
            let mut m = parent.map().expect("map parent");
            for (i, b) in m.as_mut_slice().iter_mut().enumerate() {
                *b = (i & 0xff) as u8;
            }
        }

        let outer = parent.subview(64, &[128]).expect("outer subview");
        assert_eq!(outer.plane_offset(), Some(64));
        let inner = outer.subview(32, &[64]).expect("inner subview");
        assert_eq!(
            inner.plane_offset(),
            Some(96),
            "offsets add once, not twice (64 + 32)"
        );

        let m = inner.map().expect("map nested subview");
        for (i, b) in m.as_slice().iter().enumerate() {
            assert_eq!(
                *b,
                ((i + 96) & 0xff) as u8,
                "nested window byte {i} must be parent[{}], not a compounded offset",
                i + 96
            );
        }
    }

    /// `set_format` must clear the IOSurface storage offset, not just the
    /// wrapper field.
    ///
    /// The mirror of `set_plane_offset_moves_the_iosurface_map_window`, and
    /// the reason the fix for it is a set/clear pair rather than one arm:
    /// `set_format` deliberately drops stride and offset when the format
    /// changes, because neither is necessarily valid for the new one. It
    /// dropped them with the same Linux-gated match the setter had, so
    /// clearing on macOS left `plane_offset()` reporting `None` while
    /// `map()` still started at the old offset -- a stale window instead of
    /// a lost one, and the failure mode that making the setter take effect
    /// would otherwise have introduced.
    #[test]
    fn set_format_clears_the_iosurface_map_window() {
        use crate::{PixelFormat, Tensor, TensorTrait};

        const PARENT: usize = 256;
        const OFFSET: usize = 64;

        let mut t = Tensor::<u8>::new(&[PARENT], Some(TensorMemory::DmaBuf), None).expect("alloc");
        {
            let mut m = t.map().expect("map parent");
            for (i, b) in m.as_mut_slice().iter_mut().enumerate() {
                *b = (i & 0xff) as u8;
            }
        }

        // An 8x8 greyscale window carrying an offset, so there is something
        // to clear. The surface is a 256-byte byte-bag, so the 64-byte window
        // plus the offset still fits.
        t.set_logical_shape(&[8, 8, 1]).expect("logical shape");
        t.set_format(PixelFormat::Grey).expect("format");
        t.set_plane_offset(OFFSET);
        assert_eq!(
            t.map().expect("map before").as_slice()[0],
            OFFSET as u8,
            "precondition: the offset is live before the format change"
        );

        // Changing the format drops the offset it cannot vouch for.
        t.set_logical_shape(&[4, 8, 3]).expect("rgb logical shape");
        t.set_format(PixelFormat::Rgb).expect("new format");
        assert_eq!(t.plane_offset(), None, "the wrapper field is cleared");
        assert_eq!(
            t.map().expect("map after").as_slice()[0],
            0,
            "map() still starts at the old offset — set_format cleared the \
             wrapper field but not the IOSurface storage (issue #161)"
        );
    }

    /// A descriptor round trip must restore the surface's pitch onto an
    /// IOSurface view import. Regression test for the second half of issue
    /// #161's IOSurface fix.
    ///
    /// `restore_imported_row_stride` was `HOST | DMABUF` only, on the
    /// grounds that nothing had reported the gap for IOSurface. A view of a
    /// pitched surface reports its parent's pitch in `strides[0]`; the import
    /// reopened the whole surface at the window's shape and, dropping that
    /// stride, read a 16-texel RGBA window at 64-byte rows over a surface
    /// whose rows are 256 bytes apart -- every row but the first sheared.
    /// The merged convert test hid it by calling `set_row_stride` by hand,
    /// which a real capsule consumer never does.
    ///
    /// Unlike D3D11 (whose exclusion stands: a staging pitch is the local
    /// driver's), an IOSurface's `bytesPerRow` is a property of the shared
    /// surface, so the producer's stride is the consumer's.
    #[test]
    fn descriptor_import_restores_the_iosurface_pitch_onto_a_view() {
        use crate::{Region, Tensor, TensorDyn, TensorTrait};

        // Width 50 RGBA: a 200-byte natural row, which IOSurface pads to a
        // 64-aligned 256-byte pitch. The two must differ or this test cannot
        // tell a restored pitch from a dropped one.
        let parent = Tensor::<u8>::image(
            50,
            8,
            PixelFormat::Rgba,
            Some(TensorMemory::DmaBuf),
            crate::CpuAccess::ReadWrite,
        )
        .expect("alloc a pitched RGBA surface");
        assert_eq!(parent.memory(), TensorMemory::DmaBuf);
        let pitch = parent.effective_row_stride().expect("surface pitch");
        assert_ne!(pitch, 50 * 4, "precondition: the pitch is padded");

        let view = parent.view(Region::new(4, 2, 16, 4)).expect("view");
        assert_eq!(
            view.effective_row_stride(),
            Some(pitch),
            "a multi-row view carries its parent's pitch"
        );
        let desc = TensorDyn::from(view).descriptor_pinned(None);
        assert_eq!(
            desc.strides()[0],
            pitch as i64,
            "the descriptor reports the pitch in bytes"
        );

        let rebuilt = TensorDyn::import_descriptor(&desc).expect("import the view's descriptor");
        assert_eq!(
            rebuilt.shape(),
            &[4, 16, 4],
            "imported at the window's shape"
        );
        assert_eq!(
            rebuilt.effective_row_stride(),
            Some(pitch),
            "restore_imported_row_stride dropped the IOSurface pitch: a 16-wide \
             window over a {pitch}-byte-pitched surface would be read at 64-byte \
             rows (issue #161)"
        );
    }
}