yscv-video 0.1.8

Video decoding (H.264, HEVC), MP4 parsing, and camera I/O
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
//! Hardware-accelerated video decode backends.
//!
//! Each backend is gated behind a feature flag and platform check:
//! - `videotoolbox` — macOS/iOS: Apple VideoToolbox (H.264/HEVC)
//! - `vaapi` — Linux: VA-API (Intel/AMD GPU)
//! - `nvdec` — Linux/Windows: NVIDIA NVDEC (CUDA)
//! - `media-foundation` — Windows: Media Foundation
//!
//! All backends use raw FFI to system libraries — no external crate dependencies.
//! Use [`HwVideoDecoder::new`] for automatic backend selection with software fallback.
//!
//! # Safety contract for unsafe code in this module
//!
//! All unsafe blocks fall into these categories:
//!
//! 1. **Platform FFI calls** — VideoToolbox / VA-API / NVDEC / Media Foundation APIs.
//!    Safety: handles are validated non-null before use; error codes are checked
//!    after each call; resources are cleaned up in `Drop`.
//!
//! 2. **Callback pointer dereferences** — `refcon` / `user_data` cast back from
//!    `*mut c_void` inside platform callbacks. Safety: the pointed-to value is
//!    pinned in a `Box` that outlives the session, so the pointer is valid for
//!    the lifetime of the decoder.
//!
//! 3. **SIMD intrinsics** (NEON / SSE2) — color-space conversion (NV12/BGRA to RGB).
//!    Safety: ISA availability is guaranteed by `cfg(target_arch)` or
//!    `#[target_feature(enable)]`; pointer arithmetic stays within
//!    `stride * height` and `w * h * 3` bounds enforced by the containing loop.
//!
//! 4. **Raw pointer reads** from GPU-mapped pixel buffers.
//!    Safety: the buffer is locked (`CVPixelBufferLockBaseAddress` / `vaMapBuffer`)
//!    before access and unlocked after; dimensions come from the same API that
//!    provided the pointer.

use crate::{DecodedFrame, VideoCodec, VideoDecoder, VideoError};

// ---------------------------------------------------------------------------
// Backend enum + detection
// ---------------------------------------------------------------------------

/// Detected hardware decode backend.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HwBackend {
    VideoToolbox,
    Vaapi,
    Nvdec,
    MediaFoundation,
    Software,
}

impl std::fmt::Display for HwBackend {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::VideoToolbox => write!(f, "VideoToolbox"),
            Self::Vaapi => write!(f, "VA-API"),
            Self::Nvdec => write!(f, "NVDEC"),
            Self::MediaFoundation => write!(f, "MediaFoundation"),
            Self::Software => write!(f, "Software"),
        }
    }
}

/// Detect the best available hardware decode backend.
#[allow(unreachable_code)]
pub fn detect_hw_backend() -> HwBackend {
    #[cfg(all(target_os = "macos", feature = "videotoolbox"))]
    {
        return HwBackend::VideoToolbox;
    }
    #[cfg(all(target_os = "linux", feature = "vaapi"))]
    {
        return HwBackend::Vaapi;
    }
    #[cfg(feature = "nvdec")]
    {
        return HwBackend::Nvdec;
    }
    #[cfg(all(target_os = "windows", feature = "media-foundation"))]
    {
        return HwBackend::MediaFoundation;
    }
    HwBackend::Software
}

// ═══════════════════════════════════════════════════════════════════════════
// VideoToolbox backend (macOS/iOS)
// ═══════════════════════════════════════════════════════════════════════════

#[cfg(all(target_os = "macos", feature = "videotoolbox"))]
#[allow(
    unsafe_code,
    unsafe_op_in_unsafe_fn,
    non_camel_case_types,
    non_upper_case_globals,
    dead_code,
    improper_ctypes_definitions
)]
pub mod videotoolbox {
    use super::*;
    use std::ffi::c_void;
    use std::ptr;

    // --- Raw FFI bindings to CoreMedia / VideoToolbox frameworks ---

    type OSStatus = i32;
    type CFAllocatorRef = *const c_void;
    type CFDictionaryRef = *const c_void;
    type CMFormatDescriptionRef = *const c_void;
    type CMSampleBufferRef = *const c_void;
    type CMBlockBufferRef = *const c_void;
    type CVPixelBufferRef = *const c_void;
    type VTDecompressionSessionRef = *const c_void;
    type CMVideoCodecType = u32;
    type CFStringRef = *const c_void;
    type CFTypeRef = *const c_void;
    type CMItemCount = isize;
    type CMTime = [u8; 24]; // opaque, we pass zeros

    const kCMVideoCodecType_H264: CMVideoCodecType = 0x61766331; // 'avc1'
    const kCMVideoCodecType_HEVC: CMVideoCodecType = 0x68766331; // 'hvc1'
    // NV12 video-range: VT always delivers this reliably (Y:16-235, UV:16-240)
    const kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange: u32 = 0x34323076; // '420v'
    const kCVPixelFormatType_32BGRA: u32 = 0x42475241; // 'BGRA'

    #[repr(C)]
    struct VTDecompressionOutputCallbackRecord {
        callback: extern "C" fn(
            *mut c_void,      // decompressionOutputRefCon
            *mut c_void,      // sourceFrameRefCon
            OSStatus,         // status
            u32,              // infoFlags
            CVPixelBufferRef, // imageBuffer
            CMTime,           // presentationTimeStamp
            CMTime,           // presentationDuration
        ),
        refcon: *mut c_void,
    }

    #[allow(clippy::duplicated_attributes)]
    #[link(name = "VideoToolbox", kind = "framework")]
    #[link(name = "CoreMedia", kind = "framework")]
    #[link(name = "CoreVideo", kind = "framework")]
    #[link(name = "CoreFoundation", kind = "framework")]
    unsafe extern "C" {
        fn CMVideoFormatDescriptionCreateFromH264ParameterSets(
            allocator: CFAllocatorRef,
            parameter_set_count: usize,
            parameter_set_pointers: *const *const u8,
            parameter_set_sizes: *const usize,
            nal_unit_header_length: i32,
            format_description_out: *mut CMFormatDescriptionRef,
        ) -> OSStatus;

        fn CMVideoFormatDescriptionCreateFromHEVCParameterSets(
            allocator: CFAllocatorRef,
            parameter_set_count: usize,
            parameter_set_pointers: *const *const u8,
            parameter_set_sizes: *const usize,
            nal_unit_header_length: i32,
            extensions: CFDictionaryRef,
            format_description_out: *mut CMFormatDescriptionRef,
        ) -> OSStatus;

        fn VTDecompressionSessionCreate(
            allocator: CFAllocatorRef,
            video_format_description: CMFormatDescriptionRef,
            video_decoder_specification: CFDictionaryRef,
            destination_image_buffer_attributes: CFDictionaryRef,
            output_callback: *const VTDecompressionOutputCallbackRecord,
            decompression_session_out: *mut VTDecompressionSessionRef,
        ) -> OSStatus;

        fn VTDecompressionSessionDecodeFrame(
            session: VTDecompressionSessionRef,
            sample_buffer: CMSampleBufferRef,
            decode_flags: u32,
            source_frame_refcon: *mut c_void,
            info_flags_out: *mut u32,
        ) -> OSStatus;

        fn VTDecompressionSessionWaitForAsynchronousFrames(
            session: VTDecompressionSessionRef,
        ) -> OSStatus;

        fn VTDecompressionSessionInvalidate(session: VTDecompressionSessionRef);

        fn CMBlockBufferCreateWithMemoryBlock(
            allocator: CFAllocatorRef,
            memory_block: *const c_void,
            block_length: usize,
            block_allocator: CFAllocatorRef,
            custom_block_source: *const c_void,
            offset_to_data: usize,
            data_length: usize,
            flags: u32,
            block_buffer_out: *mut CMBlockBufferRef,
        ) -> OSStatus;

        fn CMBlockBufferReplaceDataBytes(
            source_bytes: *const c_void,
            destination_buffer: CMBlockBufferRef,
            offset_into_destination: usize,
            data_length: usize,
        ) -> OSStatus;

        fn CMSampleBufferCreateReady(
            allocator: CFAllocatorRef,
            data_buffer: CMBlockBufferRef,
            format_description: CMFormatDescriptionRef,
            num_samples: CMItemCount,
            num_sample_timing_entries: CMItemCount,
            sample_timing_array: *const c_void,
            num_sample_size_entries: CMItemCount,
            sample_size_array: *const usize,
            sample_buffer_out: *mut CMSampleBufferRef,
        ) -> OSStatus;

        fn CVPixelBufferLockBaseAddress(
            pixel_buffer: CVPixelBufferRef,
            lock_flags: u64,
        ) -> OSStatus;

        fn CVPixelBufferUnlockBaseAddress(
            pixel_buffer: CVPixelBufferRef,
            lock_flags: u64,
        ) -> OSStatus;

        fn CVPixelBufferGetBaseAddress(pixel_buffer: CVPixelBufferRef) -> *const u8;
        fn CVPixelBufferGetBaseAddressOfPlane(
            pixel_buffer: CVPixelBufferRef,
            plane: usize,
        ) -> *const u8;
        fn CVPixelBufferGetBytesPerRow(pixel_buffer: CVPixelBufferRef) -> usize;
        fn CVPixelBufferGetBytesPerRowOfPlane(
            pixel_buffer: CVPixelBufferRef,
            plane: usize,
        ) -> usize;
        fn CVPixelBufferGetWidth(pixel_buffer: CVPixelBufferRef) -> usize;
        fn CVPixelBufferGetWidthOfPlane(pixel_buffer: CVPixelBufferRef, plane: usize) -> usize;
        fn CVPixelBufferGetHeight(pixel_buffer: CVPixelBufferRef) -> usize;
        fn CVPixelBufferGetHeightOfPlane(pixel_buffer: CVPixelBufferRef, plane: usize) -> usize;
        fn CVPixelBufferGetPlaneCount(pixel_buffer: CVPixelBufferRef) -> usize;

        fn CFRelease(cf: *const c_void);

        fn CFDictionaryCreateMutable(
            allocator: CFAllocatorRef,
            capacity: isize,
            key_callbacks: *const c_void,
            value_callbacks: *const c_void,
        ) -> *mut c_void;

        fn CFDictionarySetValue(dict: *mut c_void, key: *const c_void, value: *const c_void);

        fn CFNumberCreate(
            allocator: CFAllocatorRef,
            the_type: isize,
            value_ptr: *const c_void,
        ) -> *const c_void;

        static kCFAllocatorDefault: CFAllocatorRef;
        static kCFTypeDictionaryKeyCallBacks: c_void;
        static kCFTypeDictionaryValueCallBacks: c_void;
        static kCVPixelBufferPixelFormatTypeKey: CFStringRef;
    }

    /// Decoded frame storage for callback.
    struct CallbackState {
        frames: Vec<DecodedFrame>,
    }

    extern "C" fn decode_callback(
        refcon: *mut c_void,
        _source: *mut c_void,
        status: OSStatus,
        _flags: u32,
        image_buffer: CVPixelBufferRef,
        _pts: CMTime,
        _dur: CMTime,
    ) {
        if status != 0 || image_buffer.is_null() {
            return;
        }
        // SAFETY: (category 2 + 4) refcon points to a Box<CallbackState> pinned for
        // the session lifetime; image_buffer is non-null and locked before pixel access.
        unsafe {
            let state = &mut *(refcon as *mut CallbackState);

            CVPixelBufferLockBaseAddress(image_buffer, 1); // read-only
            let w = CVPixelBufferGetWidth(image_buffer);
            let h = CVPixelBufferGetHeight(image_buffer);
            let planes = CVPixelBufferGetPlaneCount(image_buffer);

            let rgb = if planes >= 2 {
                // NV12 → RGB via NEON SIMD
                let y_ptr = CVPixelBufferGetBaseAddressOfPlane(image_buffer, 0);
                let y_stride = CVPixelBufferGetBytesPerRowOfPlane(image_buffer, 0);
                let uv_ptr = CVPixelBufferGetBaseAddressOfPlane(image_buffer, 1);
                let uv_stride = CVPixelBufferGetBytesPerRowOfPlane(image_buffer, 1);
                let mut rgb_out = vec![0u8; w * h * 3];
                nv12_bt601_to_rgb(y_ptr, y_stride, uv_ptr, uv_stride, w, h, &mut rgb_out);
                rgb_out
            } else {
                // BGRA fallback
                let base = CVPixelBufferGetBaseAddress(image_buffer);
                let stride = CVPixelBufferGetBytesPerRow(image_buffer);
                let mut out = vec![0u8; w * h * 3];
                bgra_to_rgb(base, stride, w, h, &mut out);
                out
            };
            CVPixelBufferUnlockBaseAddress(image_buffer, 1);

            state.frames.push(DecodedFrame {
                width: w,
                height: h,
                rgb8_data: rgb,
                timestamp_us: 0,
                keyframe: false,
                bit_depth: 8,
                rgb16_data: None,
            });
        }
    }

    /// Apple VideoToolbox hardware decoder.
    pub struct VideoToolboxDecoder {
        codec: VideoCodec,
        session: VTDecompressionSessionRef,
        format_desc: CMFormatDescriptionRef,
        state: Box<CallbackState>,
        sps: Vec<u8>,
        pps: Vec<u8>,
        vps: Vec<u8>,
        initialized: bool,
    }

    impl VideoToolboxDecoder {
        pub fn new(codec: VideoCodec) -> Result<Self, VideoError> {
            Ok(VideoToolboxDecoder {
                codec,
                session: ptr::null(),
                format_desc: ptr::null(),
                state: Box::new(CallbackState { frames: Vec::new() }),
                sps: Vec::new(),
                pps: Vec::new(),
                vps: Vec::new(),
                initialized: false,
            })
        }

        unsafe fn create_session(&mut self) -> Result<(), VideoError> {
            // Create format description from parameter sets
            self.format_desc = match self.codec {
                VideoCodec::H264 => {
                    let ptrs = [self.sps.as_ptr(), self.pps.as_ptr()];
                    let sizes = [self.sps.len(), self.pps.len()];
                    let mut fmt: CMFormatDescriptionRef = ptr::null();
                    let status = CMVideoFormatDescriptionCreateFromH264ParameterSets(
                        kCFAllocatorDefault,
                        2,
                        ptrs.as_ptr(),
                        sizes.as_ptr(),
                        4,
                        &mut fmt,
                    );
                    if status != 0 {
                        return Err(VideoError::Codec(format!(
                            "VT: failed to create H264 format description: {status}"
                        )));
                    }
                    fmt
                }
                VideoCodec::H265 => {
                    let ptrs = [self.vps.as_ptr(), self.sps.as_ptr(), self.pps.as_ptr()];
                    let sizes = [self.vps.len(), self.sps.len(), self.pps.len()];
                    let mut fmt: CMFormatDescriptionRef = ptr::null();
                    let status = CMVideoFormatDescriptionCreateFromHEVCParameterSets(
                        kCFAllocatorDefault,
                        3,
                        ptrs.as_ptr(),
                        sizes.as_ptr(),
                        4,
                        ptr::null(),
                        &mut fmt,
                    );
                    if status != 0 {
                        return Err(VideoError::Codec(format!(
                            "VT: failed to create HEVC format description: {status}"
                        )));
                    }
                    fmt
                }
                _ => return Err(VideoError::Codec("VT: unsupported codec".into())),
            };

            // Pixel buffer attributes: request BGRA output
            let attrs = CFDictionaryCreateMutable(
                kCFAllocatorDefault,
                1,
                &kCFTypeDictionaryKeyCallBacks,
                &kCFTypeDictionaryValueCallBacks,
            );
            // NV12 output — direct from decoder, no GPU color conversion overhead.
            // CPU-side NEON NV12→RGB is faster than VT's GPU BGRA scaler on Apple Silicon.
            let pixel_fmt = kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange;
            let fmt_num = CFNumberCreate(
                kCFAllocatorDefault,
                9, // kCFNumberSInt32Type
                &pixel_fmt as *const u32 as *const c_void,
            );
            CFDictionarySetValue(attrs, kCVPixelBufferPixelFormatTypeKey, fmt_num);

            let callback = VTDecompressionOutputCallbackRecord {
                callback: decode_callback,
                refcon: &mut *self.state as *mut CallbackState as *mut c_void,
            };

            let mut session: VTDecompressionSessionRef = ptr::null();
            let status = VTDecompressionSessionCreate(
                kCFAllocatorDefault,
                self.format_desc,
                ptr::null(),
                attrs as *const c_void,
                &callback,
                &mut session,
            );
            CFRelease(fmt_num);
            CFRelease(attrs as *const c_void);

            if status != 0 {
                return Err(VideoError::Codec(format!(
                    "VT: failed to create decompression session: {status}"
                )));
            }
            self.session = session;
            self.initialized = true;
            Ok(())
        }

        fn extract_parameter_sets(&mut self, data: &[u8]) {
            // Parse Annex B NAL units and extract SPS/PPS/VPS
            let nals = crate::parse_annex_b(data);
            for nal in &nals {
                if nal.data.is_empty() {
                    continue;
                }
                match self.codec {
                    VideoCodec::H264 => {
                        let nal_type = nal.data[0] & 0x1F;
                        match nal_type {
                            7 => self.sps = nal.data.clone(), // SPS
                            8 => self.pps = nal.data.clone(), // PPS
                            _ => {}
                        }
                    }
                    VideoCodec::H265 => {
                        let nal_type = (nal.data[0] >> 1) & 0x3F;
                        match nal_type {
                            32 => self.vps = nal.data.clone(), // VPS
                            33 => self.sps = nal.data.clone(), // SPS
                            34 => self.pps = nal.data.clone(), // PPS
                            _ => {}
                        }
                    }
                    _ => {}
                }
            }
        }
    }

    impl VideoDecoder for VideoToolboxDecoder {
        fn codec(&self) -> VideoCodec {
            self.codec
        }

        fn decode(
            &mut self,
            data: &[u8],
            timestamp_us: u64,
        ) -> Result<Option<DecodedFrame>, VideoError> {
            self.extract_parameter_sets(data);

            // Initialize session once we have parameter sets
            if !self.initialized {
                let has_params = match self.codec {
                    VideoCodec::H264 => !self.sps.is_empty() && !self.pps.is_empty(),
                    VideoCodec::H265 => {
                        !self.vps.is_empty() && !self.sps.is_empty() && !self.pps.is_empty()
                    }
                    _ => false,
                };
                if !has_params {
                    return Ok(None); // Need more data
                }
                // SAFETY: (category 1) SPS/PPS/VPS validated non-empty above; FFI calls
                // check OSStatus return codes.
                unsafe {
                    self.create_session()?;
                }
            }

            // Build single AVCC buffer from all non-param NALs in this AU.
            // One CMBlockBuffer + one DecodeFrame call per AU eliminates per-NAL FFI overhead.
            let nals = crate::parse_annex_b(data);
            let mut avcc_buf = Vec::new();
            for nal in &nals {
                if nal.data.is_empty() {
                    continue;
                }
                let is_param = match self.codec {
                    VideoCodec::H264 => matches!(nal.data[0] & 0x1F, 7 | 8),
                    VideoCodec::H265 => matches!((nal.data[0] >> 1) & 0x3F, 32..=34),
                    _ => false,
                };
                if is_param {
                    continue;
                }
                let nal_len = nal.data.len() as u32;
                avcc_buf.extend_from_slice(&nal_len.to_be_bytes());
                avcc_buf.extend_from_slice(&nal.data);
            }

            if !avcc_buf.is_empty() {
                // SAFETY: (category 1) VT session is initialized; block buffer and sample
                // buffer are checked for non-null and OSStatus == 0 before use; CFRelease
                // is called on all created CF objects.
                unsafe {
                    let mut block_buf: CMBlockBufferRef = ptr::null();
                    let mut status = CMBlockBufferCreateWithMemoryBlock(
                        kCFAllocatorDefault,
                        ptr::null(),
                        avcc_buf.len(),
                        ptr::null(),
                        ptr::null(),
                        0,
                        avcc_buf.len(),
                        0,
                        &mut block_buf,
                    );
                    if status == 0 && !block_buf.is_null() {
                        status = CMBlockBufferReplaceDataBytes(
                            avcc_buf.as_ptr() as *const c_void,
                            block_buf,
                            0,
                            avcc_buf.len(),
                        );
                        if status == 0 {
                            let sample_size = avcc_buf.len();
                            let mut sample_buf: CMSampleBufferRef = ptr::null();
                            status = CMSampleBufferCreateReady(
                                kCFAllocatorDefault,
                                block_buf,
                                self.format_desc,
                                1,
                                0,
                                ptr::null(),
                                1,
                                &sample_size,
                                &mut sample_buf,
                            );
                            if status == 0 && !sample_buf.is_null() {
                                let mut info_flags: u32 = 0;
                                let _ = VTDecompressionSessionDecodeFrame(
                                    self.session,
                                    sample_buf,
                                    1, // async decode — VT pipelines decode while we prepare next AU
                                    ptr::null_mut(),
                                    &mut info_flags,
                                );
                                CFRelease(sample_buf);
                            }
                        }
                        CFRelease(block_buf);
                    }
                }
            }

            // Wait for async frames
            if self.initialized {
                // SAFETY: (category 1) session handle validated during create_session.
                unsafe {
                    VTDecompressionSessionWaitForAsynchronousFrames(self.session);
                }
            }

            // Return last decoded frame
            let mut frame = self.state.frames.pop();
            if let Some(ref mut f) = frame {
                f.timestamp_us = timestamp_us;
            }
            Ok(frame)
        }

        fn flush(&mut self) -> Result<Vec<DecodedFrame>, VideoError> {
            if self.initialized {
                // SAFETY: (category 1) session handle validated during create_session.
                unsafe {
                    VTDecompressionSessionWaitForAsynchronousFrames(self.session);
                }
            }
            Ok(std::mem::take(&mut self.state.frames))
        }
    }

    impl Drop for VideoToolboxDecoder {
        fn drop(&mut self) {
            if self.initialized {
                // SAFETY: (category 1) session/format_desc were successfully created
                // (self.initialized guards); invalidate + release is the documented
                // teardown sequence.
                unsafe {
                    VTDecompressionSessionInvalidate(self.session);
                    if !self.format_desc.is_null() {
                        CFRelease(self.format_desc);
                    }
                }
            }
        }
    }

    // Safety: VT session is used single-threaded via &mut self
    unsafe impl Send for VideoToolboxDecoder {}

    /// Convert BGRA (from VT GPU output) to RGB8.
    /// NEON: deinterleave 16 pixels at a time via vld4/vst3.
    unsafe fn bgra_to_rgb(bgra_ptr: *const u8, stride: usize, w: usize, h: usize, rgb: &mut [u8]) {
        for row in 0..h {
            let src = bgra_ptr.add(row * stride);
            let dst = &mut rgb[row * w * 3..(row + 1) * w * 3];
            let mut col = 0usize;

            #[cfg(target_arch = "aarch64")]
            {
                use std::arch::aarch64::*;
                // Process 16 pixels per iteration: load 16×BGRA, store 16×RGB
                while col + 16 <= w {
                    let bgra = vld4q_u8(src.add(col * 4));
                    // bgra.0=B, bgra.1=G, bgra.2=R, bgra.3=A
                    let out = uint8x16x3_t(bgra.2, bgra.1, bgra.0);
                    vst3q_u8(dst.as_mut_ptr().add(col * 3), out);
                    col += 16;
                }
            }

            // Scalar tail
            while col < w {
                let s = src.add(col * 4);
                let d = col * 3;
                dst[d] = *s.add(2); // R
                dst[d + 1] = *s.add(1); // G
                dst[d + 2] = *s; // B
                col += 1;
            }
        }
    }

    /// Convert NV12 BT.601 limited range to RGB8.
    /// Uses NEON SIMD on aarch64, scalar fallback otherwise.
    #[allow(clippy::too_many_arguments)]
    unsafe fn nv12_bt601_to_rgb(
        y_ptr: *const u8,
        y_stride: usize,
        uv_ptr: *const u8,
        uv_stride: usize,
        w: usize,
        h: usize,
        rgb: &mut [u8],
    ) {
        #[cfg(target_arch = "aarch64")]
        {
            nv12_bt601_to_rgb_neon(y_ptr, y_stride, uv_ptr, uv_stride, w, h, rgb);
            return;
        }
        #[cfg(target_arch = "x86_64")]
        {
            nv12_bt601_to_rgb_sse2(y_ptr, y_stride, uv_ptr, uv_stride, w, h, rgb);
            return;
        }
        #[allow(unreachable_code)]
        nv12_bt601_to_rgb_scalar(y_ptr, y_stride, uv_ptr, uv_stride, w, h, rgb);
    }

    /// NEON-accelerated NV12 BT.601 → RGB8.
    /// Processes 8 pixels per iteration using int16 arithmetic.
    #[cfg(target_arch = "aarch64")]
    #[allow(unsafe_op_in_unsafe_fn)]
    unsafe fn nv12_bt601_to_rgb_neon(
        y_ptr: *const u8,
        y_stride: usize,
        uv_ptr: *const u8,
        uv_stride: usize,
        w: usize,
        h: usize,
        rgb: &mut [u8],
    ) {
        use std::arch::aarch64::*;

        let v16 = vdupq_n_s16(16);
        let v128 = vdupq_n_s16(128);
        let c298 = vdupq_n_s16(149); // 298/2 (work in half-scale to avoid overflow)
        let c409 = vdupq_n_s16(204); // 409/2
        let c100 = vdupq_n_s16(50); // 100/2
        let c208 = vdupq_n_s16(104); // 208/2
        let c516 = vdupq_n_s16(258u16 as i16); // 516/2 (wraps but ok for signed mul)
        let half = vdupq_n_s16(64); // 128/2

        for row in 0..h {
            let y_row = y_ptr.add(row * y_stride);
            let uv_row = uv_ptr.add((row / 2) * uv_stride);
            let dst_row = &mut rgb[row * w * 3..(row + 1) * w * 3];
            let mut col = 0usize;

            while col + 8 <= w {
                // Load 8 Y values
                let y8 = vld1_u8(y_row.add(col));
                let y16 = vreinterpretq_s16_u16(vmovl_u8(y8));
                let y_adj = vsubq_s16(y16, v16); // Y - 16

                // Load 4 UV pairs (interleaved Cb,Cr), duplicate to 8
                let uv8 = vld1_u8(uv_row.add((col / 2) * 2));
                let uv16 = vreinterpretq_s16_u16(vmovl_u8(uv8));
                // Deinterleave: cb = uv[0,2,4,6], cr = uv[1,3,5,7]
                let cb4 = vuzp1q_s16(uv16, uv16); // even indices
                let cr4 = vuzp2q_s16(uv16, uv16); // odd indices
                // Each UV pair covers 2 pixels — duplicate: [a,b,c,d] → [a,a,b,b,c,c,d,d]
                let cb = vzip1q_s16(cb4, cb4);
                let cr = vzip1q_s16(cr4, cr4);
                let cb_adj = vsubq_s16(cb, v128); // Cb - 128
                let cr_adj = vsubq_s16(cr, v128); // Cr - 128

                // BT.601: work in half-scale (>>7 instead of >>8) to stay in i16
                // c = 149 * (Y-16)
                let c_val = vmulq_s16(c298, y_adj);
                // r = (c + 204*(Cr-128) + 64) >> 7
                let r16 = vshrq_n_s16(
                    vaddq_s16(vaddq_s16(c_val, vmulq_s16(c409, cr_adj)), half),
                    7,
                );
                // g = (c - 104*(Cr-128) - 50*(Cb-128) + 64) >> 7
                let g16 = vshrq_n_s16(
                    vaddq_s16(
                        vsubq_s16(
                            vsubq_s16(c_val, vmulq_s16(c208, cr_adj)),
                            vmulq_s16(c100, cb_adj),
                        ),
                        half,
                    ),
                    7,
                );
                // b = (c + 258*(Cb-128) + 64) >> 7
                let b16 = vshrq_n_s16(
                    vaddq_s16(vaddq_s16(c_val, vmulq_s16(c516, cb_adj)), half),
                    7,
                );

                // Clamp to [0, 255] and narrow to u8
                let r8 = vqmovun_s16(vmaxq_s16(r16, vdupq_n_s16(0)));
                let g8 = vqmovun_s16(vmaxq_s16(g16, vdupq_n_s16(0)));
                let b8 = vqmovun_s16(vmaxq_s16(b16, vdupq_n_s16(0)));

                // Interleave RGB and store
                let rgb_triple = uint8x8x3_t(r8, g8, b8);
                vst3_u8(dst_row.as_mut_ptr().add(col * 3), rgb_triple);

                col += 8;
            }

            // Scalar tail
            while col < w {
                let y_val = *y_row.add(col) as i32;
                let cb_val = *uv_row.add((col / 2) * 2) as i32;
                let cr_val = *uv_row.add((col / 2) * 2 + 1) as i32;
                let c = 298 * (y_val - 16);
                let r = (c + 409 * (cr_val - 128) + 128) >> 8;
                let g = (c - 208 * (cr_val - 128) - 100 * (cb_val - 128) + 128) >> 8;
                let b = (c + 516 * (cb_val - 128) + 128) >> 8;
                let dst = col * 3;
                dst_row[dst] = r.clamp(0, 255) as u8;
                dst_row[dst + 1] = g.clamp(0, 255) as u8;
                dst_row[dst + 2] = b.clamp(0, 255) as u8;
                col += 1;
            }
        }
    }

    /// SSE2-accelerated NV12 BT.601 limited range → RGB8.
    /// Processes 8 pixels per iteration using int16 arithmetic.
    #[cfg(target_arch = "x86_64")]
    #[target_feature(enable = "sse2")]
    #[allow(unsafe_op_in_unsafe_fn)]
    unsafe fn nv12_bt601_to_rgb_sse2(
        y_ptr: *const u8,
        y_stride: usize,
        uv_ptr: *const u8,
        uv_stride: usize,
        w: usize,
        h: usize,
        rgb: &mut [u8],
    ) {
        use std::arch::x86_64::*;

        // BT.601 limited range half-scale coefficients (same as NEON path)
        let c149 = _mm_set1_epi16(149); // 298/2
        let c204 = _mm_set1_epi16(204); // 409/2
        let c50 = _mm_set1_epi16(50); // 100/2
        let c104 = _mm_set1_epi16(104); // 208/2
        let c258 = _mm_set1_epi16(258u16 as i16); // 516/2
        let v16 = _mm_set1_epi16(16);
        let v128 = _mm_set1_epi16(128);
        let half = _mm_set1_epi16(64); // 128/2
        let zero = _mm_setzero_si128();

        for row in 0..h {
            let y_row = y_ptr.add(row * y_stride);
            let uv_row = uv_ptr.add((row / 2) * uv_stride);
            let dst_row = &mut rgb[row * w * 3..(row + 1) * w * 3];
            let mut col = 0usize;

            while col + 8 <= w {
                // Load 8 Y values → i16
                let y8 = _mm_loadl_epi64(y_row.add(col) as *const __m128i);
                let y16 = _mm_unpacklo_epi8(y8, zero);
                let y_adj = _mm_sub_epi16(y16, v16); // Y - 16

                // Load 8 UV bytes (4 interleaved Cb,Cr pairs), deinterleave + duplicate
                let mut cb_buf = [0u8; 8];
                let mut cr_buf = [0u8; 8];
                for i in 0..4 {
                    cb_buf[i * 2] = *uv_row.add((col / 2 + i) * 2);
                    cb_buf[i * 2 + 1] = *uv_row.add((col / 2 + i) * 2);
                    cr_buf[i * 2] = *uv_row.add((col / 2 + i) * 2 + 1);
                    cr_buf[i * 2 + 1] = *uv_row.add((col / 2 + i) * 2 + 1);
                }
                let cb8 = _mm_loadl_epi64(cb_buf.as_ptr() as *const __m128i);
                let cr8 = _mm_loadl_epi64(cr_buf.as_ptr() as *const __m128i);
                let cb_adj = _mm_sub_epi16(_mm_unpacklo_epi8(cb8, zero), v128);
                let cr_adj = _mm_sub_epi16(_mm_unpacklo_epi8(cr8, zero), v128);

                // BT.601 half-scale: c = 149*(Y-16), >>7 at the end
                let c_val = _mm_mullo_epi16(c149, y_adj);
                // R = (c + 204*(Cr-128) + 64) >> 7
                let r16 = _mm_srai_epi16::<7>(_mm_add_epi16(
                    _mm_add_epi16(c_val, _mm_mullo_epi16(c204, cr_adj)),
                    half,
                ));
                // G = (c - 104*(Cr-128) - 50*(Cb-128) + 64) >> 7
                let g16 = _mm_srai_epi16::<7>(_mm_add_epi16(
                    _mm_sub_epi16(
                        _mm_sub_epi16(c_val, _mm_mullo_epi16(c104, cr_adj)),
                        _mm_mullo_epi16(c50, cb_adj),
                    ),
                    half,
                ));
                // B = (c + 258*(Cb-128) + 64) >> 7
                let b16 = _mm_srai_epi16::<7>(_mm_add_epi16(
                    _mm_add_epi16(c_val, _mm_mullo_epi16(c258, cb_adj)),
                    half,
                ));

                // Clamp to [0,255] and pack to u8
                let r_u8 = _mm_packus_epi16(_mm_max_epi16(r16, zero), zero);
                let g_u8 = _mm_packus_epi16(_mm_max_epi16(g16, zero), zero);
                let b_u8 = _mm_packus_epi16(_mm_max_epi16(b16, zero), zero);

                // Manual RGB interleave (SSE2 has no vst3)
                let mut rgb_buf = [0u8; 24];
                let mut r_arr = [0u8; 8];
                let mut g_arr = [0u8; 8];
                let mut b_arr = [0u8; 8];
                _mm_storel_epi64(r_arr.as_mut_ptr() as *mut __m128i, r_u8);
                _mm_storel_epi64(g_arr.as_mut_ptr() as *mut __m128i, g_u8);
                _mm_storel_epi64(b_arr.as_mut_ptr() as *mut __m128i, b_u8);
                for i in 0..8 {
                    rgb_buf[i * 3] = r_arr[i];
                    rgb_buf[i * 3 + 1] = g_arr[i];
                    rgb_buf[i * 3 + 2] = b_arr[i];
                }
                std::ptr::copy_nonoverlapping(
                    rgb_buf.as_ptr(),
                    dst_row.as_mut_ptr().add(col * 3),
                    24,
                );

                col += 8;
            }

            // Scalar tail
            while col < w {
                let y_val = *y_row.add(col) as i32;
                let cb_val = *uv_row.add((col / 2) * 2) as i32;
                let cr_val = *uv_row.add((col / 2) * 2 + 1) as i32;
                let c = 298 * (y_val - 16);
                let r = (c + 409 * (cr_val - 128) + 128) >> 8;
                let g = (c - 208 * (cr_val - 128) - 100 * (cb_val - 128) + 128) >> 8;
                let b = (c + 516 * (cb_val - 128) + 128) >> 8;
                let dst = col * 3;
                dst_row[dst] = r.clamp(0, 255) as u8;
                dst_row[dst + 1] = g.clamp(0, 255) as u8;
                dst_row[dst + 2] = b.clamp(0, 255) as u8;
                col += 1;
            }
        }
    }

    /// Scalar fallback NV12 BT.601 → RGB8.
    #[allow(unsafe_op_in_unsafe_fn)]
    unsafe fn nv12_bt601_to_rgb_scalar(
        y_ptr: *const u8,
        y_stride: usize,
        uv_ptr: *const u8,
        uv_stride: usize,
        w: usize,
        h: usize,
        rgb: &mut [u8],
    ) {
        for row in 0..h {
            let y_row = y_ptr.add(row * y_stride);
            let uv_row = uv_ptr.add((row / 2) * uv_stride);
            for col in 0..w {
                let y_val = *y_row.add(col) as i32;
                let cb_val = *uv_row.add((col / 2) * 2) as i32;
                let cr_val = *uv_row.add((col / 2) * 2 + 1) as i32;
                let c = 298 * (y_val - 16);
                let r = (c + 409 * (cr_val - 128) + 128) >> 8;
                let g = (c - 208 * (cr_val - 128) - 100 * (cb_val - 128) + 128) >> 8;
                let b = (c + 516 * (cb_val - 128) + 128) >> 8;
                let dst = (row * w + col) * 3;
                rgb[dst] = r.clamp(0, 255) as u8;
                rgb[dst + 1] = g.clamp(0, 255) as u8;
                rgb[dst + 2] = b.clamp(0, 255) as u8;
            }
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// VA-API backend (Linux)
// ═══════════════════════════════════════════════════════════════════════════

#[cfg(all(target_os = "linux", feature = "vaapi"))]
#[allow(unsafe_code, non_camel_case_types)]
pub mod vaapi {
    use super::*;
    use std::ffi::c_void;
    use std::ptr;

    // --- Raw FFI to libva ---
    type VADisplay = *mut c_void;
    type VAStatus = i32;
    type VAConfigID = u32;
    type VAContextID = u32;
    type VASurfaceID = u32;
    type VABufferID = u32;
    type VAProfile = i32;
    type VAEntrypoint = i32;

    const VA_PROFILE_H264_HIGH: VAProfile = 7;
    const VA_PROFILE_HEVC_MAIN: VAProfile = 12;
    const VA_ENTRYPOINT_VLD: VAEntrypoint = 1;
    const VA_STATUS_SUCCESS: VAStatus = 0;

    #[link(name = "va")]
    unsafe extern "C" {
        fn vaInitialize(dpy: VADisplay, major: *mut i32, minor: *mut i32) -> VAStatus;
        fn vaTerminate(dpy: VADisplay) -> VAStatus;
        fn vaCreateConfig(
            dpy: VADisplay,
            profile: VAProfile,
            entrypoint: VAEntrypoint,
            attrib_list: *const c_void,
            num_attribs: i32,
            config_id: *mut VAConfigID,
        ) -> VAStatus;
        fn vaCreateSurfaces(
            dpy: VADisplay,
            format: u32,
            width: u32,
            height: u32,
            surfaces: *mut VASurfaceID,
            num_surfaces: u32,
            attrib_list: *const c_void,
            num_attribs: u32,
        ) -> VAStatus;
        fn vaCreateContext(
            dpy: VADisplay,
            config_id: VAConfigID,
            picture_width: i32,
            picture_height: i32,
            flag: i32,
            render_targets: *mut VASurfaceID,
            num_render_targets: i32,
            context: *mut VAContextID,
        ) -> VAStatus;
        fn vaBeginPicture(
            dpy: VADisplay,
            context: VAContextID,
            render_target: VASurfaceID,
        ) -> VAStatus;
        fn vaCreateBuffer(
            dpy: VADisplay,
            context: VAContextID,
            buf_type: i32,
            size: u32,
            num_elements: u32,
            data: *const c_void,
            buf_id: *mut VABufferID,
        ) -> VAStatus;
        fn vaRenderPicture(
            dpy: VADisplay,
            context: VAContextID,
            buffers: *mut VABufferID,
            num_buffers: i32,
        ) -> VAStatus;
        fn vaEndPicture(dpy: VADisplay, context: VAContextID) -> VAStatus;
        fn vaSyncSurface(dpy: VADisplay, render_target: VASurfaceID) -> VAStatus;
        fn vaDeriveImage(dpy: VADisplay, surface: VASurfaceID, image: *mut VAImage) -> VAStatus;
        fn vaMapBuffer(dpy: VADisplay, buf_id: VABufferID, pbuf: *mut *mut c_void) -> VAStatus;
        fn vaUnmapBuffer(dpy: VADisplay, buf_id: VABufferID) -> VAStatus;
        fn vaDestroyImage(dpy: VADisplay, image_id: u32) -> VAStatus;
        fn vaDestroyBuffer(dpy: VADisplay, buf_id: VABufferID) -> VAStatus;
        fn vaDestroySurfaces(
            dpy: VADisplay,
            surfaces: *mut VASurfaceID,
            num_surfaces: i32,
        ) -> VAStatus;
        fn vaDestroyConfig(dpy: VADisplay, config_id: VAConfigID) -> VAStatus;
        fn vaDestroyContext(dpy: VADisplay, context: VAContextID) -> VAStatus;
    }

    /// VA image descriptor returned by vaDeriveImage.
    #[repr(C)]
    struct VAImage {
        image_id: u32,
        format: VAImageFormat,
        buf: VABufferID,
        width: u16,
        height: u16,
        data_size: u32,
        num_planes: u32,
        pitches: [u32; 3],
        offsets: [u32; 3],
        num_palette_entries: i32,
        entry_bytes: i32,
        component_order: [i8; 4],
    }

    #[repr(C)]
    struct VAImageFormat {
        fourcc: u32,
        byte_order: u32,
        bits_per_pixel: u32,
        depth: u32,
        red_mask: u32,
        green_mask: u32,
        blue_mask: u32,
        alpha_mask: u32,
    }

    const VA_RT_FORMAT_YUV420: u32 = 0x00000001;
    const VASliceDataBufferType: i32 = 5;

    #[link(name = "va-drm")]
    unsafe extern "C" {
        fn vaGetDisplayDRM(fd: i32) -> VADisplay;
    }

    /// VA-API hardware decoder for H.264/HEVC on Linux.
    pub struct VaapiDecoder {
        codec: VideoCodec,
        display: VADisplay,
        config: VAConfigID,
        context: VAContextID,
        surfaces: Vec<VASurfaceID>,
        width: u32,
        height: u32,
        initialized: bool,
        surfaces_created: bool,
        sw_fallback: Option<Box<dyn VideoDecoder>>,
    }

    impl VaapiDecoder {
        pub fn new(codec: VideoCodec) -> Result<Self, VideoError> {
            // Try to open DRM render node
            // SAFETY: (category 1) path is a null-terminated static byte string.
            let fd = unsafe { libc_open(b"/dev/dri/renderD128\0".as_ptr() as *const _, 2) };
            if fd < 0 {
                // No DRM device — fall back to software
                let sw: Box<dyn VideoDecoder> = match codec {
                    VideoCodec::H264 => Box::new(super::super::h264_decoder::H264Decoder::new()),
                    VideoCodec::H265 => Box::new(super::super::hevc_decoder::HevcDecoder::new()),
                    _ => return Err(VideoError::Codec("Unsupported codec".into())),
                };
                return Ok(VaapiDecoder {
                    codec,
                    display: ptr::null_mut(),
                    config: 0,
                    context: 0,
                    surfaces: Vec::new(),
                    width: 0,
                    height: 0,
                    initialized: false,
                    surfaces_created: false,
                    sw_fallback: Some(sw),
                });
            }

            // SAFETY: (category 1) fd is valid (checked >= 0 above); vaInitialize status
            // is checked and display is terminated on failure.
            unsafe {
                let display = vaGetDisplayDRM(fd);
                let mut major = 0i32;
                let mut minor = 0i32;
                let status = vaInitialize(display, &mut major, &mut minor);
                if status != VA_STATUS_SUCCESS {
                    let sw: Box<dyn VideoDecoder> = match codec {
                        VideoCodec::H264 => {
                            Box::new(super::super::h264_decoder::H264Decoder::new())
                        }
                        _ => Box::new(super::super::hevc_decoder::HevcDecoder::new()),
                    };
                    return Ok(VaapiDecoder {
                        codec,
                        display: ptr::null_mut(),
                        config: 0,
                        context: 0,
                        surfaces: Vec::new(),
                        width: 0,
                        height: 0,
                        initialized: false,
                        surfaces_created: false,
                        sw_fallback: Some(sw),
                    });
                }

                let profile = match codec {
                    VideoCodec::H264 => VA_PROFILE_H264_HIGH,
                    VideoCodec::H265 => VA_PROFILE_HEVC_MAIN,
                    _ => return Err(VideoError::Codec("Unsupported codec".into())),
                };

                let mut config_id: VAConfigID = 0;
                let status = vaCreateConfig(
                    display,
                    profile,
                    VA_ENTRYPOINT_VLD,
                    ptr::null(),
                    0,
                    &mut config_id,
                );
                if status != VA_STATUS_SUCCESS {
                    vaTerminate(display);
                    let sw: Box<dyn VideoDecoder> = match codec {
                        VideoCodec::H264 => {
                            Box::new(super::super::h264_decoder::H264Decoder::new())
                        }
                        _ => Box::new(super::super::hevc_decoder::HevcDecoder::new()),
                    };
                    return Ok(VaapiDecoder {
                        codec,
                        display: ptr::null_mut(),
                        config: 0,
                        context: 0,
                        surfaces: Vec::new(),
                        width: 0,
                        height: 0,
                        initialized: false,
                        surfaces_created: false,
                        sw_fallback: Some(sw),
                    });
                }

                Ok(VaapiDecoder {
                    codec,
                    display,
                    config: config_id,
                    context: 0,
                    surfaces: Vec::new(),
                    width: 0,
                    height: 0,
                    initialized: true,
                    surfaces_created: false,
                    sw_fallback: None,
                })
            }
        }

        /// Create surfaces and context for the given resolution.
        unsafe fn create_surfaces(&mut self, width: u32, height: u32) -> Result<(), VideoError> {
            self.width = width;
            self.height = height;
            let num_surfaces: u32 = 4;
            self.surfaces = vec![0u32; num_surfaces as usize];
            let status = vaCreateSurfaces(
                self.display,
                VA_RT_FORMAT_YUV420,
                width,
                height,
                self.surfaces.as_mut_ptr(),
                num_surfaces,
                ptr::null(),
                0,
            );
            if status != VA_STATUS_SUCCESS {
                return Err(VideoError::Codec(format!(
                    "VA-API: vaCreateSurfaces failed: {status}"
                )));
            }
            let mut ctx: VAContextID = 0;
            let status = vaCreateContext(
                self.display,
                self.config,
                width as i32,
                height as i32,
                0,
                self.surfaces.as_mut_ptr(),
                num_surfaces as i32,
                &mut ctx,
            );
            if status != VA_STATUS_SUCCESS {
                return Err(VideoError::Codec(format!(
                    "VA-API: vaCreateContext failed: {status}"
                )));
            }
            self.context = ctx;
            self.surfaces_created = true;
            Ok(())
        }

        /// Decode a single slice using the full VA-API pipeline.
        unsafe fn decode_slice(
            &mut self,
            slice_data: &[u8],
            surface_idx: usize,
        ) -> Result<Option<DecodedFrame>, VideoError> {
            let surface = self.surfaces[surface_idx % self.surfaces.len()];

            // Begin picture
            let status = vaBeginPicture(self.display, self.context, surface);
            if status != VA_STATUS_SUCCESS {
                return Err(VideoError::Codec(format!(
                    "VA-API: vaBeginPicture failed: {status}"
                )));
            }

            // Create and render slice data buffer
            let mut slice_buf: VABufferID = 0;
            let status = vaCreateBuffer(
                self.display,
                self.context,
                VASliceDataBufferType,
                slice_data.len() as u32,
                1,
                slice_data.as_ptr() as *const c_void,
                &mut slice_buf,
            );
            if status != VA_STATUS_SUCCESS {
                vaEndPicture(self.display, self.context);
                return Err(VideoError::Codec(format!(
                    "VA-API: vaCreateBuffer(SliceData) failed: {status}"
                )));
            }

            let status = vaRenderPicture(self.display, self.context, &mut slice_buf, 1);
            if status != VA_STATUS_SUCCESS {
                vaDestroyBuffer(self.display, slice_buf);
                vaEndPicture(self.display, self.context);
                return Err(VideoError::Codec(format!(
                    "VA-API: vaRenderPicture failed: {status}"
                )));
            }

            // End picture
            let status = vaEndPicture(self.display, self.context);
            if status != VA_STATUS_SUCCESS {
                vaDestroyBuffer(self.display, slice_buf);
                return Err(VideoError::Codec(format!(
                    "VA-API: vaEndPicture failed: {status}"
                )));
            }

            // Sync
            let status = vaSyncSurface(self.display, surface);
            if status != VA_STATUS_SUCCESS {
                vaDestroyBuffer(self.display, slice_buf);
                return Err(VideoError::Codec(format!(
                    "VA-API: vaSyncSurface failed: {status}"
                )));
            }

            // Derive image and readback NV12
            let mut image: VAImage = std::mem::zeroed();
            let status = vaDeriveImage(self.display, surface, &mut image);
            if status != VA_STATUS_SUCCESS {
                vaDestroyBuffer(self.display, slice_buf);
                return Err(VideoError::Codec(format!(
                    "VA-API: vaDeriveImage failed: {status}"
                )));
            }

            let mut buf_ptr: *mut c_void = ptr::null_mut();
            let status = vaMapBuffer(self.display, image.buf, &mut buf_ptr);
            if status != VA_STATUS_SUCCESS {
                vaDestroyImage(self.display, image.image_id);
                vaDestroyBuffer(self.display, slice_buf);
                return Err(VideoError::Codec(format!(
                    "VA-API: vaMapBuffer failed: {status}"
                )));
            }

            let w = image.width as usize;
            let h = image.height as usize;
            let y_pitch = image.pitches[0] as usize;
            let uv_pitch = image.pitches[1] as usize;
            let uv_offset = image.offsets[1] as usize;

            let mut rgb = vec![0u8; w * h * 3];
            super::nv12_to_rgb8(
                buf_ptr as *const u8,
                y_pitch,
                (buf_ptr as *const u8).add(uv_offset),
                uv_pitch,
                w,
                h,
                &mut rgb,
            );

            vaUnmapBuffer(self.display, image.buf);
            vaDestroyImage(self.display, image.image_id);
            vaDestroyBuffer(self.display, slice_buf);

            Ok(Some(DecodedFrame {
                width: w,
                height: h,
                rgb8_data: rgb,
                timestamp_us: 0,
                keyframe: false,
                bit_depth: 8,
                rgb16_data: None,
            }))
        }
    }

    unsafe extern "C" {
        #[link_name = "open"]
        fn libc_open(path: *const u8, flags: i32) -> i32;
    }

    impl VideoDecoder for VaapiDecoder {
        fn codec(&self) -> VideoCodec {
            self.codec
        }

        fn decode(
            &mut self,
            data: &[u8],
            timestamp_us: u64,
        ) -> Result<Option<DecodedFrame>, VideoError> {
            if let Some(ref mut sw) = self.sw_fallback {
                return sw.decode(data, timestamp_us);
            }

            // Parse Annex B NAL units
            let nals = crate::parse_annex_b(data);
            if nals.is_empty() {
                return Ok(None);
            }

            // Create surfaces on first non-empty frame if not done yet.
            // Default to 1920x1080; real implementation would parse SPS for resolution.
            if !self.surfaces_created {
                // SAFETY: (category 1) VA display was initialized successfully.
                unsafe {
                    self.create_surfaces(1920, 1080)?;
                }
            }

            // Concatenate all non-parameter NALs as slice data
            let mut slice_data = Vec::new();
            for nal in &nals {
                if nal.data.is_empty() {
                    continue;
                }
                let is_param = match self.codec {
                    VideoCodec::H264 => matches!(nal.data[0] & 0x1F, 7 | 8),
                    VideoCodec::H265 => matches!((nal.data[0] >> 1) & 0x3F, 32..=34),
                    _ => false,
                };
                if !is_param {
                    slice_data.extend_from_slice(&nal.data);
                }
            }

            if slice_data.is_empty() {
                return Ok(None);
            }

            // Full VA-API pipeline: vaBeginPicture → vaCreateBuffer(SliceData) →
            // vaRenderPicture → vaEndPicture → vaSyncSurface → vaDeriveImage →
            // vaMapBuffer → NV12→RGB readback
            // SAFETY: (category 1) surfaces/context created and status checked at each step.
            unsafe {
                let mut frame = self.decode_slice(&slice_data, 0)?;
                if let Some(ref mut f) = frame {
                    f.timestamp_us = timestamp_us;
                }
                Ok(frame)
            }
        }

        fn flush(&mut self) -> Result<Vec<DecodedFrame>, VideoError> {
            if let Some(ref mut sw) = self.sw_fallback {
                return sw.flush();
            }
            Ok(Vec::new())
        }
    }

    impl Drop for VaapiDecoder {
        fn drop(&mut self) {
            if self.initialized && !self.display.is_null() {
                // SAFETY: (category 1) display/config/context/surfaces are valid
                // (self.initialized + null checks guard); VA-API teardown order is respected.
                unsafe {
                    if self.surfaces_created {
                        if self.context != 0 {
                            vaDestroyContext(self.display, self.context);
                        }
                        if !self.surfaces.is_empty() {
                            vaDestroySurfaces(
                                self.display,
                                self.surfaces.as_mut_ptr(),
                                self.surfaces.len() as i32,
                            );
                        }
                    }
                    if self.config != 0 {
                        vaDestroyConfig(self.display, self.config);
                    }
                    vaTerminate(self.display);
                }
            }
        }
    }

    unsafe impl Send for VaapiDecoder {}
}

// ═══════════════════════════════════════════════════════════════════════════
// NVDEC backend (NVIDIA, Linux/Windows)
// ═══════════════════════════════════════════════════════════════════════════

#[cfg(feature = "nvdec")]
#[allow(
    unsafe_code,
    unsafe_op_in_unsafe_fn,
    non_camel_case_types,
    non_snake_case,
    non_upper_case_globals,
    clippy::upper_case_acronyms,
    clippy::field_reassign_with_default,
    dead_code
)]
pub mod nvdec {
    use super::*;
    use std::ffi::c_void;
    use std::ptr;

    type CUresult = i32;
    type CUcontext = *mut c_void;
    type CUvideodecoder = *mut c_void;
    type CUvideoparser = *mut c_void;
    type CUdeviceptr = u64;

    const CUDA_SUCCESS: CUresult = 0;
    const cudaVideoCodec_H264: i32 = 4;
    const cudaVideoCodec_HEVC: i32 = 8;
    const cudaVideoSurfaceFormat_NV12: i32 = 0;
    const cudaVideoChromaFormat_420: i32 = 1;

    // NVDEC parser callback types
    type PfnSequenceCallback = unsafe extern "C" fn(*mut c_void, *mut CUVIDEOFORMAT) -> i32;
    type PfnDecodePicture = unsafe extern "C" fn(*mut c_void, *mut c_void) -> i32;
    type PfnDisplayPicture = unsafe extern "C" fn(*mut c_void, *mut CUVIDPARSERDISPINFO) -> i32;

    #[repr(C)]
    struct CUVIDPARSERPARAMS {
        codec_type: i32,
        max_num_decode_surfaces: u32,
        clock_rate: u32,
        error_threshold: u32,
        max_display_delay: u32,
        reserved1: [u32; 5],
        user_data: *mut c_void,
        pfn_sequence_callback: PfnSequenceCallback,
        pfn_decode_picture: PfnDecodePicture,
        pfn_display_picture: PfnDisplayPicture,
        reserved2: [*mut c_void; 7],
        ext_video_info: *mut c_void,
    }

    #[repr(C)]
    struct CUVIDEOFORMAT {
        codec: i32,
        frame_rate_num: u32,
        frame_rate_den: u32,
        progressive_sequence: u8,
        bit_depth_luma_minus8: u8,
        bit_depth_chroma_minus8: u8,
        min_num_decode_surfaces: u8,
        coded_width: u32,
        coded_height: u32,
        // ... more fields, we only need width/height
        _pad: [u8; 256], // padding for remaining fields
    }

    #[repr(C)]
    struct CUVIDPARSERDISPINFO {
        picture_index: i32,
        progressive_frame: i32,
        top_field_first: i32,
        repeat_first_field: i32,
        timestamp: i64,
    }

    #[repr(C)]
    struct CUVIDSOURCEDATAPACKET {
        flags: u64,
        payload_size: u64,
        payload: *const u8,
        timestamp: i64,
    }

    #[repr(C)]
    struct CUVIDDECODECREATEINFO {
        code_type: i32,
        chroma_format: i32,
        output_format: i32,
        bit_depth_minus8: u32,
        ull_intra_decode_only: u32,
        reserved1: [u32; 3],
        display_area_left: i16,
        display_area_top: i16,
        display_area_right: i16,
        display_area_bottom: i16,
        ul_width: u32,
        ul_height: u32,
        ul_max_width: u32,
        ul_max_height: u32,
        ul_target_width: u32,
        ul_target_height: u32,
        ul_num_decode_surfaces: u32,
        ul_num_output_surfaces: u32,
        de_interlace_mode: i32,
        video_lock: *mut c_void,
        _pad: [u8; 128],
    }

    #[repr(C)]
    struct CUVIDPROCPARAMS {
        progressive_frame: i32,
        second_field: i32,
        top_field_first: i32,
        unpaired_field: i32,
        reserved_flags: u32,
        reserved_zero: u32,
        raw_input_dptr: u64,
        raw_input_pitch: u32,
        raw_input_format: u32,
        raw_output_dptr: u64,
        raw_output_pitch: u32,
        reserved1: u32,
        output_stream: *mut c_void,
        reserved: [u32; 16],
    }

    #[link(name = "cuda")]
    unsafe extern "C" {
        fn cuInit(flags: u32) -> CUresult;
        fn cuCtxCreate_v2(ctx: *mut CUcontext, flags: u32, device: i32) -> CUresult;
        fn cuCtxDestroy_v2(ctx: CUcontext) -> CUresult;
        fn cuMemcpyDtoH_v2(dst: *mut c_void, src: CUdeviceptr, bytes: usize) -> CUresult;
    }

    #[link(name = "nvcuvid")]
    unsafe extern "C" {
        fn cuvidCreateVideoParser(
            obj: *mut CUvideoparser,
            params: *mut CUVIDPARSERPARAMS,
        ) -> CUresult;
        fn cuvidDestroyVideoParser(obj: CUvideoparser) -> CUresult;
        fn cuvidParseVideoData(obj: CUvideoparser, packet: *mut CUVIDSOURCEDATAPACKET) -> CUresult;
        fn cuvidCreateDecoder(
            decoder: *mut CUvideodecoder,
            params: *mut CUVIDDECODECREATEINFO,
        ) -> CUresult;
        fn cuvidDestroyDecoder(decoder: CUvideodecoder) -> CUresult;
        fn cuvidDecodePicture(decoder: CUvideodecoder, pic_params: *mut c_void) -> CUresult;
        fn cuvidMapVideoFrame64(
            decoder: CUvideodecoder,
            pic_idx: i32,
            dev_ptr: *mut CUdeviceptr,
            pitch: *mut u32,
            params: *mut CUVIDPROCPARAMS,
        ) -> CUresult;
        fn cuvidUnmapVideoFrame64(decoder: CUvideodecoder, dev_ptr: CUdeviceptr) -> CUresult;
    }

    /// Shared state between NVDEC parser callbacks and decoder.
    struct NvdecState {
        decoder: CUvideodecoder,
        width: u32,
        height: u32,
        frames: Vec<DecodedFrame>,
        decoder_created: bool,
        /// Callback error propagation: set inside parser callbacks, checked after parse.
        last_error: Option<String>,
    }

    // Parser callbacks
    // SAFETY: (category 2) user_data points to Box<NvdecState> pinned for the parser
    // lifetime; fmt is provided by the NVDEC parser and valid for the call duration.
    unsafe extern "C" fn sequence_callback(user_data: *mut c_void, fmt: *mut CUVIDEOFORMAT) -> i32 {
        let state = &mut *(user_data as *mut NvdecState);
        state.width = (*fmt).coded_width;
        state.height = (*fmt).coded_height;

        if !state.decoder_created {
            let mut create_info: CUVIDDECODECREATEINFO = std::mem::zeroed();
            create_info.code_type = (*fmt).codec;
            create_info.chroma_format = cudaVideoChromaFormat_420;
            create_info.output_format = cudaVideoSurfaceFormat_NV12;
            create_info.ul_width = state.width;
            create_info.ul_height = state.height;
            create_info.ul_max_width = state.width;
            create_info.ul_max_height = state.height;
            create_info.ul_target_width = state.width;
            create_info.ul_target_height = state.height;
            create_info.ul_num_decode_surfaces = 20;
            create_info.ul_num_output_surfaces = 2;

            let status = cuvidCreateDecoder(&mut state.decoder, &mut create_info);
            if status == CUDA_SUCCESS {
                state.decoder_created = true;
            } else {
                state.last_error = Some(format!("NVDEC: cuvidCreateDecoder failed: {status}"));
            }
        }
        (*fmt).min_num_decode_surfaces as i32
    }

    // SAFETY: (category 2) user_data is a valid NvdecState pointer; pic_params
    // provided by the parser and valid for the call duration.
    unsafe extern "C" fn decode_picture_callback(
        user_data: *mut c_void,
        pic_params: *mut c_void,
    ) -> i32 {
        let state = &mut *(user_data as *mut NvdecState);
        if !state.decoder_created {
            return 0;
        }
        let status = cuvidDecodePicture(state.decoder, pic_params);
        if status != CUDA_SUCCESS {
            state.last_error = Some(format!("NVDEC: cuvidDecodePicture failed: {status}"));
            0
        } else {
            1
        }
    }

    // SAFETY: (category 2 + 4) user_data is valid NvdecState; disp_info null-checked;
    // GPU frame is mapped, copied to host NV12 buffer, and unmapped within this call.
    unsafe extern "C" fn display_picture_callback(
        user_data: *mut c_void,
        disp_info: *mut CUVIDPARSERDISPINFO,
    ) -> i32 {
        if disp_info.is_null() {
            return 1;
        }
        let state = &mut *(user_data as *mut NvdecState);
        if !state.decoder_created {
            return 0;
        }

        let info = &*disp_info;
        let mut dev_ptr: CUdeviceptr = 0;
        let mut pitch: u32 = 0;
        let mut proc_params: CUVIDPROCPARAMS = std::mem::zeroed();
        proc_params.progressive_frame = info.progressive_frame;
        proc_params.top_field_first = info.top_field_first;

        let status = cuvidMapVideoFrame64(
            state.decoder,
            info.picture_index,
            &mut dev_ptr,
            &mut pitch,
            &mut proc_params,
        );
        if status != CUDA_SUCCESS {
            state.last_error = Some(format!("NVDEC: cuvidMapVideoFrame64 failed: {status}"));
            return 0;
        }

        let w = state.width as usize;
        let h = state.height as usize;
        let p = pitch as usize;

        // Copy NV12 from GPU: Y plane + UV plane
        let y_size = p * h;
        let uv_size = p * (h / 2);
        let mut nv12 = vec![0u8; y_size + uv_size];
        cuMemcpyDtoH_v2(nv12.as_mut_ptr() as *mut c_void, dev_ptr, y_size + uv_size);
        cuvidUnmapVideoFrame64(state.decoder, dev_ptr);

        // NV12 → YUV420 planar → RGB
        let mut y = vec![0u8; w * h];
        let mut cb = vec![0u8; (w / 2) * (h / 2)];
        let mut cr = vec![0u8; (w / 2) * (h / 2)];

        for row in 0..h {
            y[row * w..(row + 1) * w].copy_from_slice(&nv12[row * p..row * p + w]);
        }
        let uv_base = y_size;
        for row in 0..(h / 2) {
            for col in 0..(w / 2) {
                cb[row * (w / 2) + col] = nv12[uv_base + row * p + col * 2];
                cr[row * (w / 2) + col] = nv12[uv_base + row * p + col * 2 + 1];
            }
        }

        let rgb =
            crate::yuv420_to_rgb8(&y, &cb, &cr, w, h).unwrap_or_else(|_| vec![128u8; w * h * 3]);

        state.frames.push(DecodedFrame {
            width: w,
            height: h,
            rgb8_data: rgb,
            timestamp_us: info.timestamp as u64,
            keyframe: false,
            bit_depth: 8,
            rgb16_data: None,
        });
        1
    }

    /// NVIDIA NVDEC hardware decoder with built-in parser.
    pub struct NvdecDecoder {
        codec: VideoCodec,
        cuda_ctx: CUcontext,
        parser: CUvideoparser,
        state: Box<NvdecState>,
        initialized: bool,
        sw_fallback: Option<Box<dyn VideoDecoder>>,
    }

    impl NvdecDecoder {
        pub fn new(codec: VideoCodec) -> Result<Self, VideoError> {
            // SAFETY: (category 1) CUDA/NVDEC init sequence; each FFI status is checked
            // and resources are freed on failure path.
            unsafe {
                let status = cuInit(0);
                if status != CUDA_SUCCESS {
                    return Ok(Self::with_sw_fallback(codec));
                }

                let mut ctx: CUcontext = ptr::null_mut();
                let status = cuCtxCreate_v2(&mut ctx, 0, 0);
                if status != CUDA_SUCCESS {
                    return Ok(Self::with_sw_fallback(codec));
                }

                let mut state = Box::new(NvdecState {
                    decoder: ptr::null_mut(),
                    width: 0,
                    height: 0,
                    frames: Vec::new(),
                    decoder_created: false,
                    last_error: None,
                });

                let nvcodec = match codec {
                    VideoCodec::H264 => cudaVideoCodec_H264,
                    VideoCodec::H265 => cudaVideoCodec_HEVC,
                    _ => return Err(VideoError::Codec("NVDEC: unsupported codec".into())),
                };

                let mut params = CUVIDPARSERPARAMS {
                    codec_type: nvcodec,
                    max_num_decode_surfaces: 20,
                    clock_rate: 0,
                    error_threshold: 100,
                    max_display_delay: 4,
                    reserved1: [0; 5],
                    user_data: &mut *state as *mut NvdecState as *mut c_void,
                    pfn_sequence_callback: sequence_callback,
                    pfn_decode_picture: decode_picture_callback,
                    pfn_display_picture: display_picture_callback,
                    reserved2: [ptr::null_mut(); 7],
                    ext_video_info: ptr::null_mut(),
                };

                let mut parser: CUvideoparser = ptr::null_mut();
                let status = cuvidCreateVideoParser(&mut parser, &mut params);
                if status != CUDA_SUCCESS {
                    cuCtxDestroy_v2(ctx);
                    return Ok(Self::with_sw_fallback(codec));
                }

                Ok(NvdecDecoder {
                    codec,
                    cuda_ctx: ctx,
                    parser,
                    state,
                    initialized: true,
                    sw_fallback: None,
                })
            }
        }

        fn with_sw_fallback(codec: VideoCodec) -> Self {
            let sw: Box<dyn VideoDecoder> = match codec {
                VideoCodec::H264 => Box::new(super::super::h264_decoder::H264Decoder::new()),
                _ => Box::new(super::super::hevc_decoder::HevcDecoder::new()),
            };
            NvdecDecoder {
                codec,
                cuda_ctx: ptr::null_mut(),
                parser: ptr::null_mut(),
                state: Box::new(NvdecState {
                    decoder: ptr::null_mut(),
                    width: 0,
                    height: 0,
                    frames: Vec::new(),
                    decoder_created: false,
                    last_error: None,
                }),
                initialized: false,
                sw_fallback: Some(sw),
            }
        }
    }

    impl VideoDecoder for NvdecDecoder {
        fn codec(&self) -> VideoCodec {
            self.codec
        }

        fn decode(
            &mut self,
            data: &[u8],
            timestamp_us: u64,
        ) -> Result<Option<DecodedFrame>, VideoError> {
            if let Some(ref mut sw) = self.sw_fallback {
                return sw.decode(data, timestamp_us);
            }

            // Feed Annex B data to NVDEC parser — callbacks handle decode + display
            // SAFETY: (category 1) parser handle is valid (self.initialized); data.as_ptr()
            // valid for data.len() bytes.
            unsafe {
                let mut packet: CUVIDSOURCEDATAPACKET = std::mem::zeroed();
                packet.payload_size = data.len() as u64;
                packet.payload = data.as_ptr();
                packet.timestamp = timestamp_us as i64;
                packet.flags = 0;

                let status = cuvidParseVideoData(self.parser, &mut packet);
                if status != CUDA_SUCCESS {
                    return Err(VideoError::Codec(format!(
                        "NVDEC: cuvidParseVideoData failed: {status}"
                    )));
                }
            }

            // Check for errors propagated from callbacks
            if let Some(err) = self.state.last_error.take() {
                return Err(VideoError::Codec(err));
            }

            // Return last decoded frame from callback
            let mut frame = self.state.frames.pop();
            if let Some(ref mut f) = frame {
                f.timestamp_us = timestamp_us;
            }
            Ok(frame)
        }

        fn flush(&mut self) -> Result<Vec<DecodedFrame>, VideoError> {
            if let Some(ref mut sw) = self.sw_fallback {
                return sw.flush();
            }
            // Send end-of-stream packet
            // SAFETY: (category 1) parser is valid; zeroed packet with EOS flag is well-formed.
            unsafe {
                let mut packet: CUVIDSOURCEDATAPACKET = std::mem::zeroed();
                packet.flags = 1; // CUVID_PKT_ENDOFSTREAM
                let _ = cuvidParseVideoData(self.parser, &mut packet);
            }
            Ok(std::mem::take(&mut self.state.frames))
        }
    }

    impl Drop for NvdecDecoder {
        fn drop(&mut self) {
            if self.initialized {
                // SAFETY: (category 1) parser/decoder/ctx are valid (self.initialized +
                // null checks); destroy order: parser -> decoder -> CUDA context.
                unsafe {
                    if !self.parser.is_null() {
                        cuvidDestroyVideoParser(self.parser);
                    }
                    if self.state.decoder_created && !self.state.decoder.is_null() {
                        cuvidDestroyDecoder(self.state.decoder);
                    }
                    if !self.cuda_ctx.is_null() {
                        cuCtxDestroy_v2(self.cuda_ctx);
                    }
                }
            }
        }
    }

    unsafe impl Send for NvdecDecoder {}
}

// ═══════════════════════════════════════════════════════════════════════════
// Media Foundation backend (Windows)
// ═══════════════════════════════════════════════════════════════════════════

#[cfg(all(target_os = "windows", feature = "media-foundation"))]
#[allow(unsafe_code, non_camel_case_types, non_snake_case)]
pub mod media_foundation {
    use super::*;
    use std::ffi::c_void;
    use std::ptr;

    type HRESULT = i32;
    type GUID = [u8; 16];

    const S_OK: HRESULT = 0;

    // MFT GUIDs for H.264/HEVC decoder
    const MFT_CATEGORY_VIDEO_DECODER: GUID = [
        0x39, 0x37, 0x03, 0xd0, 0x81, 0x4f, 0x93, 0x42, 0x86, 0x8e, 0x2f, 0x73, 0x28, 0x75, 0xc5,
        0x15,
    ];

    #[link(name = "mfplat")]
    unsafe extern "system" {
        fn MFStartup(version: u32, flags: u32) -> HRESULT;
        fn MFShutdown() -> HRESULT;
    }

    // Additional MF functions for full pipeline
    #[link(name = "mf")]
    unsafe extern "system" {
        fn MFTEnumEx(
            guid_category: *const GUID,
            flags: u32,
            input_type: *const MFT_REGISTER_TYPE_INFO,
            output_type: *const MFT_REGISTER_TYPE_INFO,
            activate: *mut *mut *mut c_void, // IMFActivate***
            count: *mut u32,
        ) -> HRESULT;

        fn MFCreateSample(sample: *mut *mut c_void) -> HRESULT; // IMFSample**
        fn MFCreateMemoryBuffer(max_len: u32, buffer: *mut *mut c_void) -> HRESULT;
    }

    #[repr(C)]
    struct MFT_REGISTER_TYPE_INFO {
        guid_major_type: GUID,
        guid_subtype: GUID,
    }

    // Well-known GUIDs
    const MFMediaType_Video: GUID = [
        0x73, 0x64, 0x69, 0x76, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b,
        0x71,
    ];
    const MFVideoFormat_H264: GUID = [
        0x48, 0x32, 0x36, 0x34, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b,
        0x71,
    ];
    const MFVideoFormat_HEVC: GUID = [
        0x48, 0x45, 0x56, 0x43, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b,
        0x71,
    ];
    const MFVideoFormat_NV12: GUID = [
        0x4e, 0x56, 0x31, 0x32, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b,
        0x71,
    ];

    // ── COM vtable offsets for IMFTransform ────────────────────────
    // IUnknown: 0=QueryInterface, 1=AddRef, 2=Release
    // IMFTransform: 3..=21
    const IMF_TRANSFORM_PROCESS_INPUT: usize = 18;
    const IMF_TRANSFORM_PROCESS_OUTPUT: usize = 19;
    const IMF_TRANSFORM_PROCESS_MESSAGE: usize = 17;

    // IMFSample vtable: AddBuffer is at index 14
    const IMF_SAMPLE_ADD_BUFFER: usize = 14;

    // IMFMediaBuffer vtable: Lock=3, Unlock=4, GetCurrentLength=5
    const IMF_MEDIA_BUFFER_LOCK: usize = 3;
    const IMF_MEDIA_BUFFER_UNLOCK: usize = 4;
    const IMF_MEDIA_BUFFER_SET_CURRENT_LENGTH: usize = 6;

    // MFT_MESSAGE_NOTIFY_BEGIN_STREAMING
    const MFT_MESSAGE_NOTIFY_BEGIN_STREAMING: u32 = 0x10000000;

    #[repr(C)]
    struct MFT_OUTPUT_DATA_BUFFER {
        stream_id: u32,
        sample: *mut c_void, // IMFSample*
        status: u32,
        events: *mut c_void, // IMFCollection*
    }

    /// Call a COM method by vtable index, returning HRESULT.
    unsafe fn com_call_0(obj: *mut c_void, vtable_idx: usize) -> HRESULT {
        let vtable = *(obj as *const *const *const c_void);
        let method: unsafe extern "system" fn(*mut c_void) -> HRESULT =
            std::mem::transmute(*vtable.add(vtable_idx));
        method(obj)
    }

    /// COM Release (vtable index 2).
    unsafe fn com_release(obj: *mut c_void) {
        if !obj.is_null() {
            let vtable = *(obj as *const *const *const c_void);
            let release: unsafe extern "system" fn(*mut c_void) -> u32 =
                std::mem::transmute(*vtable.add(2));
            release(obj);
        }
    }

    /// IMFMediaBuffer::Lock(ppbBuffer, pcbMaxLength, pcbCurrentLength)
    unsafe fn media_buffer_lock(
        buf: *mut c_void,
        data_out: *mut *mut u8,
        max_len: *mut u32,
        cur_len: *mut u32,
    ) -> HRESULT {
        let vtable = *(buf as *const *const *const c_void);
        let lock: unsafe extern "system" fn(
            *mut c_void,
            *mut *mut u8,
            *mut u32,
            *mut u32,
        ) -> HRESULT = std::mem::transmute(*vtable.add(IMF_MEDIA_BUFFER_LOCK));
        lock(buf, data_out, max_len, cur_len)
    }

    /// IMFMediaBuffer::Unlock()
    unsafe fn media_buffer_unlock(buf: *mut c_void) -> HRESULT {
        let vtable = *(buf as *const *const *const c_void);
        let unlock: unsafe extern "system" fn(*mut c_void) -> HRESULT =
            std::mem::transmute(*vtable.add(IMF_MEDIA_BUFFER_UNLOCK));
        unlock(buf)
    }

    /// IMFMediaBuffer::SetCurrentLength(cbCurrentLength)
    unsafe fn media_buffer_set_current_length(buf: *mut c_void, len: u32) -> HRESULT {
        let vtable = *(buf as *const *const *const c_void);
        let set_len: unsafe extern "system" fn(*mut c_void, u32) -> HRESULT =
            std::mem::transmute(*vtable.add(IMF_MEDIA_BUFFER_SET_CURRENT_LENGTH));
        set_len(buf, len)
    }

    /// IMFSample::AddBuffer(pBuffer)
    unsafe fn sample_add_buffer(sample: *mut c_void, buffer: *mut c_void) -> HRESULT {
        let vtable = *(sample as *const *const *const c_void);
        let add_buf: unsafe extern "system" fn(*mut c_void, *mut c_void) -> HRESULT =
            std::mem::transmute(*vtable.add(IMF_SAMPLE_ADD_BUFFER));
        add_buf(sample, buffer)
    }

    /// IMFTransform::ProcessInput(dwInputStreamID, pSample, dwFlags)
    unsafe fn transform_process_input(
        transform: *mut c_void,
        stream_id: u32,
        sample: *mut c_void,
        flags: u32,
    ) -> HRESULT {
        let vtable = *(transform as *const *const *const c_void);
        let process: unsafe extern "system" fn(*mut c_void, u32, *mut c_void, u32) -> HRESULT =
            std::mem::transmute(*vtable.add(IMF_TRANSFORM_PROCESS_INPUT));
        process(transform, stream_id, sample, flags)
    }

    /// IMFTransform::ProcessOutput(dwFlags, cOutputBufferCount, pOutputSamples, pdwStatus)
    unsafe fn transform_process_output(
        transform: *mut c_void,
        flags: u32,
        count: u32,
        output_buffers: *mut MFT_OUTPUT_DATA_BUFFER,
        status: *mut u32,
    ) -> HRESULT {
        let vtable = *(transform as *const *const *const c_void);
        let process: unsafe extern "system" fn(
            *mut c_void,
            u32,
            u32,
            *mut MFT_OUTPUT_DATA_BUFFER,
            *mut u32,
        ) -> HRESULT = std::mem::transmute(*vtable.add(IMF_TRANSFORM_PROCESS_OUTPUT));
        process(transform, flags, count, output_buffers, status)
    }

    /// IMFTransform::ProcessMessage(eMessage, ulParam)
    unsafe fn transform_process_message(
        transform: *mut c_void,
        message: u32,
        param: u64,
    ) -> HRESULT {
        let vtable = *(transform as *const *const *const c_void);
        let msg: unsafe extern "system" fn(*mut c_void, u32, u64) -> HRESULT =
            std::mem::transmute(*vtable.add(IMF_TRANSFORM_PROCESS_MESSAGE));
        msg(transform, message, param)
    }

    /// Media Foundation hardware decoder for Windows.
    ///
    /// Uses MFTEnumEx to find the system H.264/HEVC decoder MFT,
    /// then feeds NAL data via ProcessInput/ProcessOutput.
    pub struct MediaFoundationDecoder {
        codec: VideoCodec,
        initialized: bool,
        width: u32,
        height: u32,
        // COM: IMFTransform* — stored as raw pointer
        transform: *mut c_void,
        sw_fallback: Option<Box<dyn VideoDecoder>>,
    }

    impl MediaFoundationDecoder {
        pub fn new(codec: VideoCodec) -> Result<Self, VideoError> {
            // SAFETY: (category 1) MF startup/enum sequence; HRESULT checked at each step;
            // falls back to software on any failure.
            unsafe {
                let hr = MFStartup(0x00020070, 0); // MF_VERSION = 2.0
                if hr != S_OK {
                    return Ok(Self::with_sw_fallback(codec));
                }

                // Find decoder MFT
                let subtype = match codec {
                    VideoCodec::H264 => MFVideoFormat_H264,
                    VideoCodec::H265 => MFVideoFormat_HEVC,
                    _ => return Err(VideoError::Codec("MF: unsupported codec".into())),
                };

                let input_info = MFT_REGISTER_TYPE_INFO {
                    guid_major_type: MFMediaType_Video,
                    guid_subtype: subtype,
                };

                let mut activate: *mut *mut c_void = ptr::null_mut();
                let mut count: u32 = 0;
                let hr = MFTEnumEx(
                    &MFT_CATEGORY_VIDEO_DECODER,
                    0x00000070, // MFT_ENUM_FLAG_SYNCMFT | ASYNCMFT | HARDWARE | SORTANDFILTER
                    &input_info,
                    ptr::null(),
                    &mut activate,
                    &mut count,
                );

                if hr != S_OK || count == 0 || activate.is_null() {
                    MFShutdown();
                    return Ok(Self::with_sw_fallback(codec));
                }

                // Activate first decoder MFT
                // IMFActivate::ActivateObject(IID_IMFTransform, &transform)
                // This requires COM vtable call — simplified here
                // For production: use windows crate or manual vtable dispatch
                let _first_activate = *activate;

                // COM cleanup would free activate array here
                // For now, store as initialized with SW fallback for actual decode
                // Full COM vtable dispatch requires IUnknown::QueryInterface pattern
                Ok(MediaFoundationDecoder {
                    codec,
                    initialized: true,
                    width: 0,
                    height: 0,
                    transform: ptr::null_mut(), // Would be IMFTransform* after ActivateObject
                    sw_fallback: Some(match codec {
                        VideoCodec::H264 => {
                            Box::new(super::super::h264_decoder::H264Decoder::new())
                                as Box<dyn VideoDecoder>
                        }
                        _ => Box::new(super::super::hevc_decoder::HevcDecoder::new()),
                    }),
                })
            }
        }

        fn with_sw_fallback(codec: VideoCodec) -> Self {
            let sw: Box<dyn VideoDecoder> = match codec {
                VideoCodec::H264 => Box::new(super::super::h264_decoder::H264Decoder::new()),
                _ => Box::new(super::super::hevc_decoder::HevcDecoder::new()),
            };
            MediaFoundationDecoder {
                codec,
                initialized: false,
                width: 0,
                height: 0,
                transform: ptr::null_mut(),
                sw_fallback: Some(sw),
            }
        }

        /// Feed NAL data to the MFT via ProcessInput, then drain ProcessOutput.
        unsafe fn feed_and_drain(
            &mut self,
            data: &[u8],
            timestamp_us: u64,
        ) -> Result<Option<DecodedFrame>, VideoError> {
            if self.transform.is_null() {
                return Err(VideoError::Codec("MF: transform not initialized".into()));
            }

            // Create IMFMediaBuffer, lock, copy NAL data, unlock
            let mut media_buf: *mut c_void = ptr::null_mut();
            let hr = MFCreateMemoryBuffer(data.len() as u32, &mut media_buf);
            if hr != S_OK || media_buf.is_null() {
                return Err(VideoError::Codec(format!(
                    "MF: MFCreateMemoryBuffer failed: {hr:#X}"
                )));
            }

            let mut buf_ptr: *mut u8 = ptr::null_mut();
            let mut max_len: u32 = 0;
            let mut cur_len: u32 = 0;
            let hr = media_buffer_lock(media_buf, &mut buf_ptr, &mut max_len, &mut cur_len);
            if hr != S_OK {
                com_release(media_buf);
                return Err(VideoError::Codec(format!(
                    "MF: IMFMediaBuffer::Lock failed: {hr:#X}"
                )));
            }
            std::ptr::copy_nonoverlapping(data.as_ptr(), buf_ptr, data.len());
            media_buffer_unlock(media_buf);
            media_buffer_set_current_length(media_buf, data.len() as u32);

            // Create IMFSample, add buffer
            let mut sample: *mut c_void = ptr::null_mut();
            let hr = MFCreateSample(&mut sample);
            if hr != S_OK || sample.is_null() {
                com_release(media_buf);
                return Err(VideoError::Codec(format!(
                    "MF: MFCreateSample failed: {hr:#X}"
                )));
            }
            let hr = sample_add_buffer(sample, media_buf);
            if hr != S_OK {
                com_release(sample);
                com_release(media_buf);
                return Err(VideoError::Codec(format!(
                    "MF: IMFSample::AddBuffer failed: {hr:#X}"
                )));
            }

            // ProcessInput
            let hr = transform_process_input(self.transform, 0, sample, 0);
            com_release(sample);
            com_release(media_buf);
            if hr != S_OK {
                return Err(VideoError::Codec(format!(
                    "MF: ProcessInput failed: {hr:#X}"
                )));
            }

            // ProcessOutput — try to drain one frame
            let mut out_sample: *mut c_void = ptr::null_mut();
            let hr_sample = MFCreateSample(&mut out_sample);
            if hr_sample != S_OK || out_sample.is_null() {
                return Ok(None);
            }

            let mut output_buf = MFT_OUTPUT_DATA_BUFFER {
                stream_id: 0,
                sample: out_sample,
                status: 0,
                events: ptr::null_mut(),
            };
            let mut proc_status: u32 = 0;
            let hr =
                transform_process_output(self.transform, 0, 1, &mut output_buf, &mut proc_status);
            if hr != S_OK {
                com_release(out_sample);
                // MF_E_TRANSFORM_NEED_MORE_INPUT = 0xC00D6D72
                return Ok(None);
            }

            // Would extract NV12 from output sample and convert to RGB here.
            // For now, release and return None — full extraction requires
            // IMFSample::ConvertToContiguousBuffer + NV12→RGB.
            com_release(out_sample);
            Ok(None)
        }
    }

    impl VideoDecoder for MediaFoundationDecoder {
        fn codec(&self) -> VideoCodec {
            self.codec
        }

        fn decode(
            &mut self,
            data: &[u8],
            timestamp_us: u64,
        ) -> Result<Option<DecodedFrame>, VideoError> {
            if let Some(ref mut sw) = self.sw_fallback {
                return sw.decode(data, timestamp_us);
            }
            // Full MFT pipeline: ProcessInput → ProcessOutput
            // SAFETY: (category 1) transform handle validated; COM methods called via vtable.
            unsafe { self.feed_and_drain(data, timestamp_us) }
        }

        fn flush(&mut self) -> Result<Vec<DecodedFrame>, VideoError> {
            if let Some(ref mut sw) = self.sw_fallback {
                return sw.flush();
            }
            Ok(Vec::new())
        }
    }

    impl Drop for MediaFoundationDecoder {
        fn drop(&mut self) {
            if self.initialized {
                // SAFETY: (category 1) COM release + MFShutdown; transform null-checked.
                unsafe {
                    if !self.transform.is_null() {
                        com_release(self.transform);
                    }
                    MFShutdown();
                }
            }
        }
    }

    unsafe impl Send for MediaFoundationDecoder {}
}

// ═══════════════════════════════════════════════════════════════════════════
// Shared NV12 → RGB8 helper (BT.601 limited-range, Q8 fixed-point)
// ═══════════════════════════════════════════════════════════════════════════

/// Convert NV12 (Y plane + interleaved UV plane) to packed RGB8 using BT.601
/// limited-range coefficients with Q8 fixed-point arithmetic.
///
/// This is a platform-independent helper used by VA-API, NVDEC, and
/// MediaFoundation backends after GPU→host readback.
///
/// # Safety
///
/// `y_ptr` must point to at least `y_stride * h` readable bytes.
/// `uv_ptr` must point to at least `uv_stride * (h / 2)` readable bytes.
/// `rgb` must have length >= `w * h * 3`.
#[allow(unsafe_code, unsafe_op_in_unsafe_fn)]
pub unsafe fn nv12_to_rgb8(
    y_ptr: *const u8,
    y_stride: usize,
    uv_ptr: *const u8,
    uv_stride: usize,
    w: usize,
    h: usize,
    rgb: &mut [u8],
) {
    // BT.601 limited range (Y: 16-235, Cb/Cr: 16-240):
    //   R = clip((298*(Y-16) + 409*(Cr-128) + 128) >> 8)
    //   G = clip((298*(Y-16) - 208*(Cr-128) - 100*(Cb-128) + 128) >> 8)
    //   B = clip((298*(Y-16) + 516*(Cb-128) + 128) >> 8)
    for row in 0..h {
        let y_row = y_ptr.add(row * y_stride);
        let uv_row = uv_ptr.add((row / 2) * uv_stride);
        let dst_base = row * w * 3;
        for col in 0..w {
            let y_val = *y_row.add(col) as i32;
            let cb_val = *uv_row.add((col / 2) * 2) as i32;
            let cr_val = *uv_row.add((col / 2) * 2 + 1) as i32;
            let c = 298 * (y_val - 16);
            let r = (c + 409 * (cr_val - 128) + 128) >> 8;
            let g = (c - 208 * (cr_val - 128) - 100 * (cb_val - 128) + 128) >> 8;
            let b = (c + 516 * (cb_val - 128) + 128) >> 8;
            let dst = dst_base + col * 3;
            rgb[dst] = r.clamp(0, 255) as u8;
            rgb[dst + 1] = g.clamp(0, 255) as u8;
            rgb[dst + 2] = b.clamp(0, 255) as u8;
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// Auto-dispatch decoder
// ═══════════════════════════════════════════════════════════════════════════

/// Hardware-accelerated video decoder with automatic software fallback.
pub struct HwVideoDecoder {
    backend: HwBackend,
    inner: Box<dyn VideoDecoder>,
}

impl HwVideoDecoder {
    /// Create a decoder with automatic backend selection.
    pub fn new(codec: VideoCodec) -> Result<Self, VideoError> {
        let backend = detect_hw_backend();

        let hw_result: Result<Box<dyn VideoDecoder>, VideoError> = match backend {
            #[cfg(all(target_os = "macos", feature = "videotoolbox"))]
            HwBackend::VideoToolbox => videotoolbox::VideoToolboxDecoder::new(codec)
                .map(|d| Box::new(d) as Box<dyn VideoDecoder>),

            #[cfg(all(target_os = "linux", feature = "vaapi"))]
            HwBackend::Vaapi => {
                vaapi::VaapiDecoder::new(codec).map(|d| Box::new(d) as Box<dyn VideoDecoder>)
            }

            #[cfg(feature = "nvdec")]
            HwBackend::Nvdec => {
                nvdec::NvdecDecoder::new(codec).map(|d| Box::new(d) as Box<dyn VideoDecoder>)
            }

            #[cfg(all(target_os = "windows", feature = "media-foundation"))]
            HwBackend::MediaFoundation => media_foundation::MediaFoundationDecoder::new(codec)
                .map(|d| Box::new(d) as Box<dyn VideoDecoder>),

            _ => Err(VideoError::Codec("No hardware backend available".into())),
        };

        match hw_result {
            Ok(decoder) => Ok(HwVideoDecoder {
                backend,
                inner: decoder,
            }),
            Err(_) => {
                let sw: Box<dyn VideoDecoder> = match codec {
                    VideoCodec::H264 => Box::new(super::h264_decoder::H264Decoder::new()),
                    VideoCodec::H265 => Box::new(super::hevc_decoder::HevcDecoder::new()),
                    _ => return Err(VideoError::Codec(format!("Unsupported codec: {codec:?}"))),
                };
                Ok(HwVideoDecoder {
                    backend: HwBackend::Software,
                    inner: sw,
                })
            }
        }
    }

    pub fn backend(&self) -> HwBackend {
        self.backend
    }
    pub fn is_hardware(&self) -> bool {
        self.backend != HwBackend::Software
    }
}

impl VideoDecoder for HwVideoDecoder {
    fn codec(&self) -> VideoCodec {
        self.inner.codec()
    }
    fn decode(&mut self, data: &[u8], ts: u64) -> Result<Option<DecodedFrame>, VideoError> {
        self.inner.decode(data, ts)
    }
    fn flush(&mut self) -> Result<Vec<DecodedFrame>, VideoError> {
        self.inner.flush()
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// Tests
// ═══════════════════════════════════════════════════════════════════════════

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

    #[test]
    fn detect_backend() {
        let backend = detect_hw_backend();
        println!("Detected backend: {backend}");
    }

    #[test]
    fn hw_decoder_fallback_h264() {
        let decoder = HwVideoDecoder::new(VideoCodec::H264).unwrap();
        // Without features, falls back to software
        println!("H264 backend: {}", decoder.backend());
    }

    #[test]
    fn hw_decoder_fallback_hevc() {
        let decoder = HwVideoDecoder::new(VideoCodec::H265).unwrap();
        println!("HEVC backend: {}", decoder.backend());
    }
}