mediadecode-ffmpeg 0.9.0

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

use std::vec::Vec;

use mediaframe::frame::Rotation;

use crate::FfmpegBytes;

use derive_more::IsVariant;
use ffmpeg_next::codec::Parameters;

use crate::demuxer::{
  DemuxError, ParametersAlloc, ParametersCopy, ParametersMissing, ParametersTooLarge,
};

/// Per-`VideoPacket` extras.
#[derive(Clone, Debug, Default)]
pub struct VideoPacketExtra {
  stream_index: i32,
  byte_pos: Option<i64>,
  side_data: Vec<SideDataEntry>,
}

impl VideoPacketExtra {
  /// Constructs a `VideoPacketExtra` with the given stream index.
  /// `byte_pos` defaults to `None` and `side_data` to empty.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn new(stream_index: i32) -> Self {
    Self {
      stream_index,
      byte_pos: None,
      side_data: Vec::new(),
    }
  }

  /// Returns the source `AVStream.index`.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn stream_index(&self) -> i32 {
    self.stream_index
  }

  /// Returns the byte position of the packet in the input file, or
  /// `None` if unknown.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn byte_pos(&self) -> Option<i64> {
    self.byte_pos
  }

  /// Returns the raw side-data entries from `AVPacket.side_data`.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn side_data(&self) -> &[SideDataEntry] {
    self.side_data.as_slice()
  }

  /// Sets the stream index (consuming builder).
  #[cfg_attr(not(tarpaulin), inline(always))]
  #[must_use]
  pub const fn with_stream_index(mut self, value: i32) -> Self {
    self.stream_index = value;
    self
  }
  /// Sets the byte position (consuming builder).
  #[cfg_attr(not(tarpaulin), inline(always))]
  #[must_use]
  pub const fn with_byte_pos(mut self, value: Option<i64>) -> Self {
    self.byte_pos = value;
    self
  }
  /// Sets the side-data list (consuming builder).
  #[cfg_attr(not(tarpaulin), inline(always))]
  #[must_use]
  pub fn with_side_data(mut self, value: Vec<SideDataEntry>) -> Self {
    self.side_data = value;
    self
  }

  /// Sets the stream index in place.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn set_stream_index(&mut self, value: i32) -> &mut Self {
    self.stream_index = value;
    self
  }
  /// Sets the byte position in place.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn set_byte_pos(&mut self, value: Option<i64>) -> &mut Self {
    self.byte_pos = value;
    self
  }
  /// Sets the side-data list in place.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn set_side_data(&mut self, value: Vec<SideDataEntry>) -> &mut Self {
    self.side_data = value;
    self
  }
}

/// Per-`VideoFrame` extras carrying everything the unified
/// `mediadecode::ColorInfo` doesn't already cover.
#[derive(Clone, Debug, Default)]
pub struct VideoFrameExtra {
  sample_aspect_ratio: Option<(u32, u32)>,
  picture_type: PictureType,
  key_frame: bool,
  interlaced: bool,
  top_field_first: bool,
  best_effort_timestamp: Option<i64>,
  mastering_display: Option<MasteringDisplay>,
  content_light_level: Option<ContentLightLevel>,
  smpte_timecode: Vec<u32>,
  side_data: Vec<SideDataEntry>,
}

impl VideoFrameExtra {
  /// Constructs an empty `VideoFrameExtra` (all fields at default).
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn new() -> Self {
    Self {
      sample_aspect_ratio: None,
      picture_type: PictureType::Unspecified,
      key_frame: false,
      interlaced: false,
      top_field_first: false,
      best_effort_timestamp: None,
      mastering_display: None,
      content_light_level: None,
      smpte_timecode: Vec::new(),
      side_data: Vec::new(),
    }
  }

  /// Sample aspect ratio (par numerator / denominator), `None` if 1:1
  /// or unspecified.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn sample_aspect_ratio(&self) -> Option<(u32, u32)> {
    self.sample_aspect_ratio
  }
  /// Frame picture type (I/P/B/etc.).
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn picture_type(&self) -> PictureType {
    self.picture_type
  }
  /// `True` if this frame is a key frame.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn key_frame(&self) -> bool {
    self.key_frame
  }
  /// `True` if the frame is interlaced.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn interlaced(&self) -> bool {
    self.interlaced
  }
  /// `True` if the top field is first (only meaningful with `interlaced`).
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn top_field_first(&self) -> bool {
    self.top_field_first
  }
  /// FFmpeg's heuristic best-effort PTS, or `None` if unknown.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn best_effort_timestamp(&self) -> Option<i64> {
    self.best_effort_timestamp
  }
  /// HDR10 mastering-display metadata, if present on the source frame.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn mastering_display(&self) -> Option<MasteringDisplay> {
    self.mastering_display
  }
  /// HDR10 content-light-level.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn content_light_level(&self) -> Option<ContentLightLevel> {
    self.content_light_level
  }
  /// SMPTE ST 12-M timecode entries (raw 32-bit BCD-packed values).
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn smpte_timecode(&self) -> &[u32] {
    self.smpte_timecode.as_slice()
  }
  /// Raw side-data entries from `AVFrame.side_data`.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn side_data(&self) -> &[SideDataEntry] {
    self.side_data.as_slice()
  }

  /// Sets the sample aspect ratio (consuming builder).
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn with_sample_aspect_ratio(mut self, value: Option<(u32, u32)>) -> Self {
    self.sample_aspect_ratio = value;
    self
  }
  /// Sets the picture type (consuming builder).
  #[cfg_attr(not(tarpaulin), inline(always))]
  #[must_use]
  pub const fn with_picture_type(mut self, value: PictureType) -> Self {
    self.picture_type = value;
    self
  }
  /// Sets the key-frame flag (consuming builder).
  #[cfg_attr(not(tarpaulin), inline(always))]
  #[must_use]
  pub const fn with_key_frame(mut self, value: bool) -> Self {
    self.key_frame = value;
    self
  }
  /// Sets the interlaced flag (consuming builder).
  #[cfg_attr(not(tarpaulin), inline(always))]
  #[must_use]
  pub const fn with_interlaced(mut self, value: bool) -> Self {
    self.interlaced = value;
    self
  }
  /// Sets the top-field-first flag (consuming builder).
  #[cfg_attr(not(tarpaulin), inline(always))]
  #[must_use]
  pub const fn with_top_field_first(mut self, value: bool) -> Self {
    self.top_field_first = value;
    self
  }
  /// Sets the best-effort timestamp (consuming builder).
  #[cfg_attr(not(tarpaulin), inline(always))]
  #[must_use]
  pub const fn with_best_effort_timestamp(mut self, value: Option<i64>) -> Self {
    self.best_effort_timestamp = value;
    self
  }
  /// Sets the mastering-display metadata (consuming builder).
  #[cfg_attr(not(tarpaulin), inline(always))]
  #[must_use]
  pub const fn with_mastering_display(mut self, value: Option<MasteringDisplay>) -> Self {
    self.mastering_display = value;
    self
  }
  /// Sets the content-light-level metadata (consuming builder).
  #[cfg_attr(not(tarpaulin), inline(always))]
  #[must_use]
  pub const fn with_content_light_level(mut self, value: Option<ContentLightLevel>) -> Self {
    self.content_light_level = value;
    self
  }
  /// Sets the SMPTE timecode list (consuming builder).
  #[cfg_attr(not(tarpaulin), inline(always))]
  #[must_use]
  pub fn with_smpte_timecode(mut self, value: Vec<u32>) -> Self {
    self.smpte_timecode = value;
    self
  }
  /// Sets the side-data list (consuming builder).
  #[cfg_attr(not(tarpaulin), inline(always))]
  #[must_use]
  pub fn with_side_data(mut self, value: Vec<SideDataEntry>) -> Self {
    self.side_data = value;
    self
  }

  /// Sets the sample aspect ratio in place.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn set_sample_aspect_ratio(&mut self, value: Option<(u32, u32)>) -> &mut Self {
    self.sample_aspect_ratio = value;
    self
  }
  /// Sets the picture type in place.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn set_picture_type(&mut self, value: PictureType) -> &mut Self {
    self.picture_type = value;
    self
  }
  /// Sets the key-frame flag in place.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn set_key_frame(&mut self, value: bool) -> &mut Self {
    self.key_frame = value;
    self
  }
  /// Sets the interlaced flag in place.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn set_interlaced(&mut self, value: bool) -> &mut Self {
    self.interlaced = value;
    self
  }
  /// Sets the top-field-first flag in place.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn set_top_field_first(&mut self, value: bool) -> &mut Self {
    self.top_field_first = value;
    self
  }
  /// Sets the best-effort timestamp in place.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn set_best_effort_timestamp(&mut self, value: Option<i64>) -> &mut Self {
    self.best_effort_timestamp = value;
    self
  }
  /// Sets the mastering-display metadata in place.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn set_mastering_display(&mut self, value: Option<MasteringDisplay>) -> &mut Self {
    self.mastering_display = value;
    self
  }
  /// Sets the content-light-level metadata in place.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn set_content_light_level(&mut self, value: Option<ContentLightLevel>) -> &mut Self {
    self.content_light_level = value;
    self
  }
  /// Sets the SMPTE timecode list in place.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn set_smpte_timecode(&mut self, value: Vec<u32>) -> &mut Self {
    self.smpte_timecode = value;
    self
  }
  /// Sets the side-data list in place.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn set_side_data(&mut self, value: Vec<SideDataEntry>) -> &mut Self {
    self.side_data = value;
    self
  }
}

/// Per-`AudioPacket` extras.
#[derive(Clone, Debug, Default)]
pub struct AudioPacketExtra {
  stream_index: i32,
  byte_pos: Option<i64>,
  side_data: Vec<SideDataEntry>,
}

impl AudioPacketExtra {
  /// Constructs an `AudioPacketExtra` with the given stream index.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn new(stream_index: i32) -> Self {
    Self {
      stream_index,
      byte_pos: None,
      side_data: Vec::new(),
    }
  }

  /// Returns the source `AVStream.index`.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn stream_index(&self) -> i32 {
    self.stream_index
  }
  /// Returns the byte position, or `None` if unknown.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn byte_pos(&self) -> Option<i64> {
    self.byte_pos
  }
  /// Returns the raw side-data entries.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn side_data(&self) -> &[SideDataEntry] {
    self.side_data.as_slice()
  }

  /// Sets the stream index (consuming builder).
  #[cfg_attr(not(tarpaulin), inline(always))]
  #[must_use]
  pub const fn with_stream_index(mut self, value: i32) -> Self {
    self.stream_index = value;
    self
  }
  /// Sets the byte position (consuming builder).
  #[cfg_attr(not(tarpaulin), inline(always))]
  #[must_use]
  pub const fn with_byte_pos(mut self, value: Option<i64>) -> Self {
    self.byte_pos = value;
    self
  }
  /// Sets the side-data list (consuming builder).
  #[cfg_attr(not(tarpaulin), inline(always))]
  #[must_use]
  pub fn with_side_data(mut self, value: Vec<SideDataEntry>) -> Self {
    self.side_data = value;
    self
  }

  /// Sets the stream index in place.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn set_stream_index(&mut self, value: i32) -> &mut Self {
    self.stream_index = value;
    self
  }
  /// Sets the byte position in place.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn set_byte_pos(&mut self, value: Option<i64>) -> &mut Self {
    self.byte_pos = value;
    self
  }
  /// Sets the side-data list in place.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn set_side_data(&mut self, value: Vec<SideDataEntry>) -> &mut Self {
    self.side_data = value;
    self
  }
}

/// Per-`AudioFrame` extras.
#[derive(Clone, Debug, Default)]
pub struct AudioFrameExtra {
  best_effort_timestamp: Option<i64>,
  side_data: Vec<SideDataEntry>,
}

impl AudioFrameExtra {
  /// Constructs an empty `AudioFrameExtra`.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn new() -> Self {
    Self {
      best_effort_timestamp: None,
      side_data: Vec::new(),
    }
  }

  /// FFmpeg's heuristic best-effort PTS, or `None` if unknown.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn best_effort_timestamp(&self) -> Option<i64> {
    self.best_effort_timestamp
  }
  /// Returns the raw side-data entries.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn side_data(&self) -> &[SideDataEntry] {
    self.side_data.as_slice()
  }

  /// Sets the best-effort timestamp (consuming builder).
  #[cfg_attr(not(tarpaulin), inline(always))]
  #[must_use]
  pub const fn with_best_effort_timestamp(mut self, value: Option<i64>) -> Self {
    self.best_effort_timestamp = value;
    self
  }
  /// Sets the side-data list (consuming builder).
  #[cfg_attr(not(tarpaulin), inline(always))]
  #[must_use]
  pub fn with_side_data(mut self, value: Vec<SideDataEntry>) -> Self {
    self.side_data = value;
    self
  }

  /// Sets the best-effort timestamp in place.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn set_best_effort_timestamp(&mut self, value: Option<i64>) -> &mut Self {
    self.best_effort_timestamp = value;
    self
  }
  /// Sets the side-data list in place.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn set_side_data(&mut self, value: Vec<SideDataEntry>) -> &mut Self {
    self.side_data = value;
    self
  }
}

/// Per-`SubtitlePacket` extras.
#[derive(Clone, Debug, Default)]
pub struct SubtitlePacketExtra {
  stream_index: i32,
  language: Option<[u8; 3]>,
  forced: bool,
  side_data: Vec<SideDataEntry>,
}

impl SubtitlePacketExtra {
  /// Constructs a `SubtitlePacketExtra` with the given stream index.
  /// `side_data` defaults to empty.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn new(stream_index: i32) -> Self {
    Self {
      stream_index,
      language: None,
      forced: false,
      side_data: Vec::new(),
    }
  }

  /// Returns the source `AVStream.index`.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn stream_index(&self) -> i32 {
    self.stream_index
  }
  /// Returns the ISO 639-2/T language tag, or `None` if unspecified.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn language(&self) -> Option<[u8; 3]> {
    self.language
  }
  /// Returns whether this subtitle stream is marked "forced".
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn forced(&self) -> bool {
    self.forced
  }
  /// Returns the raw side-data entries from `AVPacket.side_data`.
  ///
  /// A subtitle packet's side data is rare but not absent — and a
  /// packet that carries *nothing else* is exactly the case this seat
  /// exists for: with no seat, a side-data-only packet has nowhere to
  /// put its only content.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn side_data(&self) -> &[SideDataEntry] {
    self.side_data.as_slice()
  }

  /// Sets the stream index (consuming builder).
  #[cfg_attr(not(tarpaulin), inline(always))]
  #[must_use]
  pub const fn with_stream_index(mut self, value: i32) -> Self {
    self.stream_index = value;
    self
  }
  /// Sets the language tag (consuming builder).
  #[cfg_attr(not(tarpaulin), inline(always))]
  #[must_use]
  pub const fn with_language(mut self, value: Option<[u8; 3]>) -> Self {
    self.language = value;
    self
  }
  /// Sets the side-data list (consuming builder).
  #[cfg_attr(not(tarpaulin), inline(always))]
  #[must_use]
  pub fn with_side_data(mut self, value: Vec<SideDataEntry>) -> Self {
    self.side_data = value;
    self
  }
  /// Sets the side-data list in place.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn set_side_data(&mut self, value: Vec<SideDataEntry>) -> &mut Self {
    self.side_data = value;
    self
  }
  /// Sets the forced flag (consuming builder).
  #[cfg_attr(not(tarpaulin), inline(always))]
  #[must_use]
  pub const fn with_forced(mut self, value: bool) -> Self {
    self.forced = value;
    self
  }

  /// Sets the stream index in place.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn set_stream_index(&mut self, value: i32) -> &mut Self {
    self.stream_index = value;
    self
  }
  /// Sets the language tag in place.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn set_language(&mut self, value: Option<[u8; 3]>) -> &mut Self {
    self.language = value;
    self
  }
  /// Sets the forced flag in place.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn set_forced(&mut self, value: bool) -> &mut Self {
    self.forced = value;
    self
  }
}

/// Per-`SubtitleFrame` extras.
#[derive(Clone, Debug, Default)]
pub struct SubtitleFrameExtra {
  start_display_time: u32,
  end_display_time: u32,
}

impl SubtitleFrameExtra {
  /// Constructs a `SubtitleFrameExtra`.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn new(start_display_time: u32, end_display_time: u32) -> Self {
    Self {
      start_display_time,
      end_display_time,
    }
  }

  /// `AVSubtitle.start_display_time` — milliseconds from `pts`.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn start_display_time(&self) -> u32 {
    self.start_display_time
  }
  /// `AVSubtitle.end_display_time` — milliseconds from `pts`.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn end_display_time(&self) -> u32 {
    self.end_display_time
  }

  /// Sets the start display time (consuming builder).
  #[cfg_attr(not(tarpaulin), inline(always))]
  #[must_use]
  pub const fn with_start_display_time(mut self, value: u32) -> Self {
    self.start_display_time = value;
    self
  }
  /// Sets the end display time (consuming builder).
  #[cfg_attr(not(tarpaulin), inline(always))]
  #[must_use]
  pub const fn with_end_display_time(mut self, value: u32) -> Self {
    self.end_display_time = value;
    self
  }

  /// Sets the start display time in place.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn set_start_display_time(&mut self, value: u32) -> &mut Self {
    self.start_display_time = value;
    self
  }
  /// Sets the end display time in place.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn set_end_display_time(&mut self, value: u32) -> &mut Self {
    self.end_display_time = value;
    self
  }
}

/// Where the first stored row and column of a still belong on screen —
/// the eight orientations EXIF names, tags 1 through 8.
///
/// # How it reaches us
///
/// Not through `AVFrame.metadata`, which is where an earlier reading of
/// libavcodec put it. **Measured**, against this build, by feeding
/// mjpeg a JPEG whose EXIF IFD carries each orientation in turn: for a
/// recognised tag (1..=8) the decoder emits an
/// `AV_FRAME_DATA_DISPLAYMATRIX` frame side-data entry and puts
/// *nothing* in the metadata dictionary; only an out-of-range tag (0,
/// 9, …) is left to fall through to the dictionary, as the string
/// `"      9"`. So the display matrix is the road, and the metadata
/// dictionary is where malformed tags go to be ignored.
///
/// The matrix that arrives is the one below, in units of 65536 (the
/// 16.16 fixed point `libavutil/display.h` specifies), with
/// `(a, b, c, d)` the entries at indices 0, 1, 3, 4:
///
/// | tag | variant | a | b | c | d |
/// |-----|---------|---|---|---|---|
/// | 1 | [`TopLeft`](Self::TopLeft)         |  1 |  0 |  0 |  1 |
/// | 2 | [`TopRight`](Self::TopRight)       | -1 |  0 |  0 |  1 |
/// | 3 | [`BottomRight`](Self::BottomRight) | -1 |  0 |  0 | -1 |
/// | 4 | [`BottomLeft`](Self::BottomLeft)   |  1 |  0 |  0 | -1 |
/// | 5 | [`LeftTop`](Self::LeftTop)         |  0 |  1 |  1 |  0 |
/// | 6 | [`RightTop`](Self::RightTop)       |  0 |  1 | -1 |  0 |
/// | 7 | [`RightBottom`](Self::RightBottom) |  0 | -1 | -1 |  0 |
/// | 8 | [`LeftBottom`](Self::LeftBottom)   |  0 | -1 |  1 |  0 |
///
/// # Why a vocabulary of its own
///
/// [`mediaframe::frame::Rotation`] is this crate's home for a quarter
/// turn and is reused by [`Self::rotation`] — but it names four values
/// and there are eight. The other four are *mirrored*, and a rotation
/// vocabulary cannot hold a reflection. The same gap shows up one
/// level down in FFmpeg's own API: `av_display_rotation_get` answers
/// `-180` for **both** tag 2 and tag 3, `-90` for both 5 and 6, and
/// `90` for both 7 and 8 — reading only the angle loses the mirror on
/// half the vocabulary. This type is the eight-value reading that does
/// not.
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash, IsVariant)]
#[non_exhaustive]
pub enum ImageOrientation {
  /// Tag 1 — stored as displayed. The default and the overwhelming
  /// majority of files.
  #[default]
  TopLeft,
  /// Tag 2 — mirrored horizontally.
  TopRight,
  /// Tag 3 — turned half way round.
  BottomRight,
  /// Tag 4 — mirrored vertically.
  BottomLeft,
  /// Tag 5 — transposed (mirrored, then a quarter turn clockwise).
  LeftTop,
  /// Tag 6 — a quarter turn clockwise.
  RightTop,
  /// Tag 7 — transverse (mirrored, then three quarter turns
  /// clockwise).
  RightBottom,
  /// Tag 8 — three quarter turns clockwise.
  LeftBottom,
  /// A display matrix none of the eight names, carried verbatim as
  /// **all nine** of its words.
  ///
  /// Reachable: the display matrix is a general affine transform, and
  /// a container (a MOV `tkhd`, a hand-built stream) may carry an
  /// arbitrary one. Rather than answer `TopLeft` for a transform this
  /// vocabulary cannot name — the silent-loss failure this crate
  /// refuses everywhere else — the whole matrix rides along and
  /// [`Self::to_exif_code`] admits it has no tag for it.
  ///
  /// **All nine words, not the four that carry the orientation.** The
  /// escape's job is to lose nothing: a matrix with the right linear
  /// part and a translation, or a perspective term, is *not* one of
  /// the eight, and carrying only `[a, b, c, d]` would have thrown
  /// away the very words that made it different. That is the same
  /// collapse the escape exists to prevent, one level in.
  Other([i32; 9]),
}

impl ImageOrientation {
  /// One 16.16 fixed-point unit — the value a display-matrix entry
  /// takes for ±1.
  const UNIT: i32 = 1 << 16;

  /// One 2.30 fixed-point unit — the value the matrix's `w` term takes
  /// for 1, and the only value it takes for a picture that is merely
  /// turned rather than projected.
  const PERSPECTIVE_UNIT: i32 = 1 << 30;

  /// The number of bytes an `AV_FRAME_DATA_DISPLAYMATRIX` entry
  /// carries: nine `int32_t`, per `libavutil/display.h`.
  pub const DISPLAY_MATRIX_BYTES: usize = 9 * core::mem::size_of::<i32>();

  /// The nine-word matrix a named orientation stands for — the exact
  /// inverse of what [`Self::from_display_matrix`] reads, and for
  /// [`Self::Other`] the words it was handed, unchanged.
  ///
  /// `libavutil/display.h` lays the matrix out row-major as
  ///
  /// ```text
  /// | a b u |     | 0 1 2 |
  /// | c d v |  =  | 3 4 5 |
  /// | x y w |     | 6 7 8 |
  /// ```
  ///
  /// where `a b c d x y` are 16.16 fixed point and `u v w` are 2.30.
  /// A named orientation puts the rotation-or-reflection in `a b c d`,
  /// no translation in `x y`, no perspective in `u v`, and unity in
  /// `w`.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn matrix(&self) -> [i32; 9] {
    match self {
      Self::Other(matrix) => *matrix,
      named => {
        let [a, b, c, d] = named.linear();
        [a, b, 0, c, d, 0, 0, 0, Self::PERSPECTIVE_UNIT]
      }
    }
  }

  /// Reads an orientation out of the raw bytes of an
  /// `AV_FRAME_DATA_DISPLAYMATRIX` side-data entry.
  ///
  /// `None` when `bytes` is not exactly
  /// [`Self::DISPLAY_MATRIX_BYTES`] long — a malformed entry is not an
  /// orientation, and guessing one from a truncated matrix would be
  /// the invention this seat exists to avoid.
  ///
  /// The entries are `int32_t` in **native** byte order: the side data
  /// is a C array as it sits in memory, not a wire format.
  pub fn from_display_matrix(bytes: &[u8]) -> Option<Self> {
    if bytes.len() != Self::DISPLAY_MATRIX_BYTES {
      return None;
    }
    let mut matrix = [0i32; 9];
    for (index, word) in matrix.iter_mut().enumerate() {
      let mut raw = [0u8; 4];
      raw.copy_from_slice(&bytes[index * 4..index * 4 + 4]);
      *word = i32::from_ne_bytes(raw);
    }
    Some(Self::from_matrix(matrix))
  }

  /// The orientation a whole nine-word matrix names. Anything but the
  /// eight rides [`Self::Other`], whole.
  ///
  /// **A named variant requires the other five words to be canonical**
  /// — no translation in `x`/`y`, no perspective in `u`/`v`, and unity
  /// in `w` — not merely a linear part that matches. A matrix that
  /// turns the picture *and* shifts it is not "turned"; answering
  /// `RightTop` for it would drop the shift on the floor, which is the
  /// collapse the escape exists to prevent.
  fn from_matrix(matrix: [i32; 9]) -> Self {
    const P: i32 = ImageOrientation::UNIT;
    const N: i32 = -ImageOrientation::UNIT;
    const W: i32 = ImageOrientation::PERSPECTIVE_UNIT;
    match matrix {
      [P, 0, 0, 0, P, 0, 0, 0, W] => Self::TopLeft,
      [N, 0, 0, 0, P, 0, 0, 0, W] => Self::TopRight,
      [N, 0, 0, 0, N, 0, 0, 0, W] => Self::BottomRight,
      [P, 0, 0, 0, N, 0, 0, 0, W] => Self::BottomLeft,
      [0, P, 0, P, 0, 0, 0, 0, W] => Self::LeftTop,
      [0, P, 0, N, 0, 0, 0, 0, W] => Self::RightTop,
      [0, N, 0, N, 0, 0, 0, 0, W] => Self::RightBottom,
      [0, N, 0, P, 0, 0, 0, 0, W] => Self::LeftBottom,
      other => Self::Other(other),
    }
  }

  /// The EXIF tag value, 1 through 8.
  ///
  /// `None` for [`Self::Other`]: it names a transform EXIF has no tag
  /// for, and there is no number to invent for it.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn to_exif_code(&self) -> Option<u16> {
    Some(match self {
      Self::TopLeft => 1,
      Self::TopRight => 2,
      Self::BottomRight => 3,
      Self::BottomLeft => 4,
      Self::LeftTop => 5,
      Self::RightTop => 6,
      Self::RightBottom => 7,
      Self::LeftBottom => 8,
      Self::Other(_) => return None,
    })
  }

  /// Decodes an EXIF tag value. `None` outside 1..=8 — never a silent
  /// collapse onto [`Self::TopLeft`], which is what a viewer that
  /// clamps an out-of-range tag ends up showing.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn from_exif_code(code: u16) -> Option<Self> {
    Some(match code {
      1 => Self::TopLeft,
      2 => Self::TopRight,
      3 => Self::BottomRight,
      4 => Self::BottomLeft,
      5 => Self::LeftTop,
      6 => Self::RightTop,
      7 => Self::RightBottom,
      8 => Self::LeftBottom,
      _ => return None,
    })
  }

  /// `true` when displaying the picture correctly requires a
  /// reflection as well as a turn — EXIF tags 2, 4, 5 and 7.
  ///
  /// Read off the sign of the linear part's determinant, which is what
  /// a reflection *is*, so [`Self::Other`] answers too.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn is_mirrored(&self) -> bool {
    let [a, b, c, d] = self.linear();
    // Every entry is 0 or ±65536 for the eight named orientations, and
    // an arbitrary matrix's entries are bounded by `i32`; widening to
    // `i64` keeps the products exact for both.
    (a as i64) * (d as i64) - (b as i64) * (c as i64) < 0
  }

  /// The quarter turn, clockwise, in the EXIF specification's
  /// mirror-then-rotate decomposition — expressed in this workspace's
  /// existing rotation vocabulary.
  ///
  /// `None` for [`Self::Other`], whose transform need not be a
  /// multiple of 90° at all.
  ///
  /// This is the specification's decomposition, not a measurement:
  /// what was measured here is which matrix carries which *tag* (see
  /// the type's own docs), and the tag's meaning is EXIF's to define.
  /// [`Self::is_mirrored`] supplies the half a [`Rotation`] cannot
  /// hold.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn rotation(&self) -> Option<Rotation> {
    Some(match self {
      Self::TopLeft | Self::TopRight => Rotation::D0,
      Self::RightTop | Self::LeftTop => Rotation::D90,
      Self::BottomRight | Self::BottomLeft => Rotation::D180,
      Self::LeftBottom | Self::RightBottom => Rotation::D270,
      Self::Other(_) => return None,
    })
  }

  /// The linear part of the display matrix this orientation stands
  /// for, `[a, b, c, d]` in 16.16 fixed point — matrix indices 0, 1, 3
  /// and 4.
  ///
  /// A **projection**, not the whole value: for [`Self::Other`] it
  /// drops the five words that made the matrix unnameable. Use
  /// [`Self::matrix`] when nothing may be lost; this is for the
  /// rotation-and-reflection question, which the four words answer on
  /// their own.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn linear(&self) -> [i32; 4] {
    const P: i32 = ImageOrientation::UNIT;
    const N: i32 = -ImageOrientation::UNIT;
    match self {
      Self::TopLeft => [P, 0, 0, P],
      Self::TopRight => [N, 0, 0, P],
      Self::BottomRight => [N, 0, 0, N],
      Self::BottomLeft => [P, 0, 0, N],
      Self::LeftTop => [0, P, P, 0],
      Self::RightTop => [0, P, N, 0],
      Self::RightBottom => [0, N, N, 0],
      Self::LeftBottom => [0, N, P, 0],
      Self::Other(matrix) => [matrix[0], matrix[1], matrix[3], matrix[4]],
    }
  }
}

/// Per-[`ImageFrame`](mediadecode::frame::ImageFrame) extras — cover
/// art, an embedded thumbnail, a poster frame.
///
/// **One seat, deliberately.** This household is minimal at birth
/// because a still image's `AVFrame` carries almost nothing a motion
/// frame's does: no picture type, no field order, no best-effort
/// timestamp, no SAR worth a seat. What it does carry is side data,
/// and that is what is here.
///
/// **EXIF orientation takes a seat here**, read off the frame's
/// `AV_FRAME_DATA_DISPLAYMATRIX` side data — see [`ImageOrientation`]
/// for the measurement that establishes that road, and for why an
/// earlier reading of libavcodec (which put orientation in
/// `AVFrame.metadata`) was wrong about where it arrives.
///
/// **An ICC profile** arrives as side data too
/// (`AV_FRAME_DATA_ICC_PROFILE`) and does *not* get a seat: it is a
/// payload, not a fact — kilobytes of colour transform this crate has
/// no vocabulary for and no business parsing. [`Self::side_data`]
/// carries it unparsed and whole for a consumer that does. That is the
/// line: a fact a picture cannot be displayed correctly without is
/// typed; a payload only a specialist reads rides raw.
#[derive(Clone, Debug, Default)]
pub struct ImageFrameExtra {
  orientation: Option<ImageOrientation>,
  side_data: Vec<SideDataEntry>,
}

impl ImageFrameExtra {
  /// Constructs an `ImageFrameExtra` with no orientation and no side
  /// data.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn new() -> Self {
    Self {
      orientation: None,
      side_data: Vec::new(),
    }
  }

  /// How the picture should be turned for display, when the file said.
  ///
  /// `None` means the frame carried no display matrix — the ordinary
  /// case for a still with no EXIF orientation tag, and also what an
  /// **out-of-range** tag produces, because libavcodec emits no matrix
  /// for one. A malformed matrix (not nine `int32_t`) is `None` too.
  /// In every one of those cases the raw entry, if there was one, is
  /// still in [`Self::side_data`].
  ///
  /// A consumer that ignores this displays a sideways photograph.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn orientation(&self) -> Option<ImageOrientation> {
    self.orientation
  }

  /// Returns the raw side-data entries from `AVFrame.side_data` —
  /// `AV_FRAME_DATA_ICC_PROFILE` and the display matrix among them.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn side_data(&self) -> &[SideDataEntry] {
    self.side_data.as_slice()
  }

  /// Sets the orientation (consuming builder).
  #[cfg_attr(not(tarpaulin), inline(always))]
  #[must_use]
  pub const fn with_orientation(mut self, value: Option<ImageOrientation>) -> Self {
    self.orientation = value;
    self
  }

  /// Sets the side-data list (consuming builder).
  #[cfg_attr(not(tarpaulin), inline(always))]
  #[must_use]
  pub fn with_side_data(mut self, value: Vec<SideDataEntry>) -> Self {
    self.side_data = value;
    self
  }

  /// Sets the orientation in place.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn set_orientation(&mut self, value: Option<ImageOrientation>) -> &mut Self {
    self.orientation = value;
    self
  }

  /// Sets the side-data list in place.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn set_side_data(&mut self, value: Vec<SideDataEntry>) -> &mut Self {
    self.side_data = value;
    self
  }
}

/// Picture type per `AVFrame.pict_type`.
#[derive(Copy, Clone, Debug, Default, Eq, PartialEq, Hash, IsVariant)]
#[non_exhaustive]
pub enum PictureType {
  /// Unspecified / unset.
  #[default]
  Unspecified,
  /// Intra (I-frame).
  I,
  /// Predicted (P-frame).
  P,
  /// Bi-directional predicted (B-frame).
  B,
  /// S(GMC)-VOP from MPEG-4.
  S,
  /// Switching Intra (H.264).
  Si,
  /// Switching Predicted (H.264).
  Sp,
  /// Bi-predicted intra (BI-frame).
  Bi,
}

/// Raw side-data entry carrying the FFmpeg type id and the unparsed
/// byte buffer. Type ids correspond to FFmpeg's
/// `AV_FRAME_DATA_*` / `AV_PKT_DATA_*` constants — see
/// `libavutil/frame.h` and `libavcodec/packet.h`.
///
/// The payload is an `FfmpegBytes` — see the [module docs](self) for the
/// reason it is not a `Vec<u8>`.
#[derive(Clone, Debug)]
pub struct SideDataEntry {
  kind: i32,
  data: FfmpegBytes,
}

impl SideDataEntry {
  /// Constructs a `SideDataEntry`.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn new(kind: i32, data: FfmpegBytes) -> Self {
    Self { kind, data }
  }

  /// FFmpeg side-data type id.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn kind(&self) -> i32 {
    self.kind
  }
  /// Side-data payload as raw bytes.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn data(&self) -> &[u8] {
    self.data.as_slice()
  }
  /// The payload's carrier, for a consumer that wants to keep the
  /// bytes without copying them again.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn data_ref(&self) -> &FfmpegBytes {
    &self.data
  }

  /// Sets the type id (consuming builder).
  #[cfg_attr(not(tarpaulin), inline(always))]
  #[must_use]
  pub const fn with_kind(mut self, value: i32) -> Self {
    self.kind = value;
    self
  }
  /// Sets the payload (consuming builder).
  #[cfg_attr(not(tarpaulin), inline(always))]
  #[must_use]
  pub fn with_data(mut self, value: FfmpegBytes) -> Self {
    self.data = value;
    self
  }

  /// Sets the type id in place.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn set_kind(&mut self, value: i32) -> &mut Self {
    self.kind = value;
    self
  }
  /// Sets the payload in place.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn set_data(&mut self, value: FfmpegBytes) -> &mut Self {
    self.data = value;
    self
  }
}

/// HDR10 mastering display metadata.
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct MasteringDisplay {
  display_primaries: [(u32, u32); 3],
  white_point: (u32, u32),
  max_luminance: (u32, u32),
  min_luminance: (u32, u32),
}

impl MasteringDisplay {
  /// Constructs a `MasteringDisplay`.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn new(
    display_primaries: [(u32, u32); 3],
    white_point: (u32, u32),
    max_luminance: (u32, u32),
    min_luminance: (u32, u32),
  ) -> Self {
    Self {
      display_primaries,
      white_point,
      max_luminance,
      min_luminance,
    }
  }

  /// Display primary chromaticities `(x, y)` for R, G, B in CIE 1931
  /// (each as `(num, den)` rational, with `den` non-zero).
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn display_primaries(&self) -> [(u32, u32); 3] {
    self.display_primaries
  }
  /// White-point chromaticity `(x, y)` as rationals.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn white_point(&self) -> (u32, u32) {
    self.white_point
  }
  /// Maximum luminance in `0.0001 cd/m²` units (rational `(num, den)`).
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn max_luminance(&self) -> (u32, u32) {
    self.max_luminance
  }
  /// Minimum luminance in `0.0001 cd/m²` units.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn min_luminance(&self) -> (u32, u32) {
    self.min_luminance
  }

  /// Sets the display primaries (consuming builder).
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn with_display_primaries(mut self, value: [(u32, u32); 3]) -> Self {
    self.display_primaries = value;
    self
  }
  /// Sets the white point (consuming builder).
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn with_white_point(mut self, value: (u32, u32)) -> Self {
    self.white_point = value;
    self
  }
  /// Sets the max luminance (consuming builder).
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn with_max_luminance(mut self, value: (u32, u32)) -> Self {
    self.max_luminance = value;
    self
  }
  /// Sets the min luminance (consuming builder).
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn with_min_luminance(mut self, value: (u32, u32)) -> Self {
    self.min_luminance = value;
    self
  }

  /// Sets the display primaries in place.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn set_display_primaries(&mut self, value: [(u32, u32); 3]) -> &mut Self {
    self.display_primaries = value;
    self
  }
  /// Sets the white point in place.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn set_white_point(&mut self, value: (u32, u32)) -> &mut Self {
    self.white_point = value;
    self
  }
  /// Sets the max luminance in place.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn set_max_luminance(&mut self, value: (u32, u32)) -> &mut Self {
    self.max_luminance = value;
    self
  }
  /// Sets the min luminance in place.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn set_min_luminance(&mut self, value: (u32, u32)) -> &mut Self {
    self.min_luminance = value;
    self
  }
}

/// HDR10 content light level (`AV_FRAME_DATA_CONTENT_LIGHT_LEVEL`).
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Default)]
pub struct ContentLightLevel {
  max_cll: u32,
  max_fall: u32,
}

impl ContentLightLevel {
  /// Constructs a `ContentLightLevel`.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn new(max_cll: u32, max_fall: u32) -> Self {
    Self { max_cll, max_fall }
  }

  /// Maximum content light level (cd/m²).
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn max_cll(&self) -> u32 {
    self.max_cll
  }
  /// Maximum frame-average light level (cd/m²).
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn max_fall(&self) -> u32 {
    self.max_fall
  }

  /// Sets `max_cll` (consuming builder).
  #[cfg_attr(not(tarpaulin), inline(always))]
  #[must_use]
  pub const fn with_max_cll(mut self, value: u32) -> Self {
    self.max_cll = value;
    self
  }
  /// Sets `max_fall` (consuming builder).
  #[cfg_attr(not(tarpaulin), inline(always))]
  #[must_use]
  pub const fn with_max_fall(mut self, value: u32) -> Self {
    self.max_fall = value;
    self
  }

  /// Sets `max_cll` in place.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn set_max_cll(&mut self, value: u32) -> &mut Self {
    self.max_cll = value;
    self
  }
  /// Sets `max_fall` in place.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn set_max_fall(&mut self, value: u32) -> &mut Self {
    self.max_fall = value;
    self
  }
}

// ---------------------------------------------------------------------------
//  The demux tier's carriers.
// ---------------------------------------------------------------------------

/// Per-`DataPacket` extras — timecode, KLV, timed ID3.
///
/// The same three seats as [`VideoPacketExtra`]. The side-data list was
/// left off at first — data demuxers carry their whole payload in the
/// packet body — and then earned its place: a packet with no body and
/// only side data is a real packet, and without this seat its only
/// content would have nowhere to go.
#[derive(Clone, Debug, Default)]
pub struct DataPacketExtra {
  stream_index: i32,
  byte_pos: Option<i64>,
  side_data: Vec<SideDataEntry>,
}

impl DataPacketExtra {
  /// Constructs a `DataPacketExtra` with the given stream index.
  /// `byte_pos` defaults to `None` and `side_data` to empty.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn new(stream_index: i32) -> Self {
    Self {
      stream_index,
      byte_pos: None,
      side_data: Vec::new(),
    }
  }

  /// Returns the source `AVStream.index`.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn stream_index(&self) -> i32 {
    self.stream_index
  }
  /// Returns the byte position of the packet in the input file, or
  /// `None` if unknown.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn byte_pos(&self) -> Option<i64> {
    self.byte_pos
  }
  /// Returns the raw side-data entries from `AVPacket.side_data`.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn side_data(&self) -> &[SideDataEntry] {
    self.side_data.as_slice()
  }

  /// Sets the stream index (consuming builder).
  #[cfg_attr(not(tarpaulin), inline(always))]
  #[must_use]
  pub const fn with_stream_index(mut self, value: i32) -> Self {
    self.stream_index = value;
    self
  }
  /// Sets the byte position (consuming builder).
  #[cfg_attr(not(tarpaulin), inline(always))]
  #[must_use]
  pub const fn with_byte_pos(mut self, value: Option<i64>) -> Self {
    self.byte_pos = value;
    self
  }
  /// Sets the side-data list (consuming builder).
  #[cfg_attr(not(tarpaulin), inline(always))]
  #[must_use]
  pub fn with_side_data(mut self, value: Vec<SideDataEntry>) -> Self {
    self.side_data = value;
    self
  }

  /// Sets the stream index in place.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn set_stream_index(&mut self, value: i32) -> &mut Self {
    self.stream_index = value;
    self
  }
  /// Sets the byte position in place.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn set_byte_pos(&mut self, value: Option<i64>) -> &mut Self {
    self.byte_pos = value;
    self
  }
  /// Sets the side-data list in place.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn set_side_data(&mut self, value: Vec<SideDataEntry>) -> &mut Self {
    self.side_data = value;
    self
  }
}

/// Per-`AttachmentPacket` extras — fonts, cover art.
///
/// `synthesized` records where the payload came from, which is not a
/// detail: an attachment track's single packet is either a real packet
/// the container stores (cover art, which libavformat parks in
/// `AVStream.attached_pic`) or one this crate builds out of the
/// track's codec extradata (fonts, whose bytes never appear in the
/// packet stream at all). A consumer chasing a payload that looks
/// wrong needs to know which.
#[derive(Clone, Debug, Default)]
pub struct AttachmentPacketExtra {
  stream_index: i32,
  synthesized: bool,
}

impl AttachmentPacketExtra {
  /// Constructs an `AttachmentPacketExtra` with the given stream index.
  /// `synthesized` defaults to `false`.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn new(stream_index: i32) -> Self {
    Self {
      stream_index,
      synthesized: false,
    }
  }

  /// Returns the source `AVStream.index`.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn stream_index(&self) -> i32 {
    self.stream_index
  }
  /// `true` when the payload was built from the track's codec
  /// extradata rather than taken from a packet the container stores.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn synthesized(&self) -> bool {
    self.synthesized
  }

  /// Sets the stream index (consuming builder).
  #[cfg_attr(not(tarpaulin), inline(always))]
  #[must_use]
  pub const fn with_stream_index(mut self, value: i32) -> Self {
    self.stream_index = value;
    self
  }
  /// Sets the synthesized flag (consuming builder).
  #[cfg_attr(not(tarpaulin), inline(always))]
  #[must_use]
  pub const fn with_synthesized(mut self, value: bool) -> Self {
    self.synthesized = value;
    self
  }

  /// Sets the stream index in place.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn set_stream_index(&mut self, value: i32) -> &mut Self {
    self.stream_index = value;
    self
  }
  /// Sets the synthesized flag in place.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn set_synthesized(&mut self, value: bool) -> &mut Self {
    self.synthesized = value;
    self
  }
}

/// The heap bytes an `AVCodecParameters` holds — measured, never
/// allocated.
///
/// See [`bounded_clone_parameters`] for the rule this measurement
/// serves and for the field-by-field inventory it is derived from.
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
pub struct ParameterFootprint {
  extradata: usize,
  extradata_payload: usize,
  coded_side_data: usize,
  channel_map: usize,
}

impl ParameterFootprint {
  /// Bytes a copy of `extradata` allocates — the payload **plus** the
  /// `AV_INPUT_BUFFER_PADDING_SIZE` trailing zeroes decoders read past
  /// the end into.
  ///
  /// The padding is counted because it is allocated: a ceiling that
  /// measured only the payload admitted a copy sixty-four bytes larger
  /// than it agreed to, once per stream. Zero when there is no
  /// extradata at all — no payload, no padding.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn extradata(&self) -> usize {
    self.extradata
  }

  /// The `extradata_size` the parameters declare — the payload alone,
  /// with no padding.
  ///
  /// [`Self::extradata`] is what a *parameter clone* costs, padding
  /// included. This is what a **carrier** costs: the synthesized
  /// attachment road copies these bytes into an [`FfmpegBytes`], which
  /// allocates exactly them, so charging the padded figure against the
  /// attachment budget would bill sixty-four bytes nobody allocates —
  /// and reject a payload sitting in the last sixty-four bytes below
  /// the ceiling that the image road, judging the same bytes, accepts.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn extradata_payload(&self) -> usize {
    self.extradata_payload
  }
  /// Bytes across every `coded_side_data` entry, plus the array of
  /// descriptors itself.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn coded_side_data(&self) -> usize {
    self.coded_side_data
  }
  /// Bytes in a custom channel map, or zero for every other layout
  /// order.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn channel_map(&self) -> usize {
    self.channel_map
  }
  /// Everything a clone of these parameters would retain.
  ///
  /// `None` on overflow — a set of declared sizes that cannot be added
  /// up is not a set anything should try to copy.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn total(&self) -> Option<usize> {
    match self.extradata.checked_add(self.coded_side_data) {
      Some(sum) => sum.checked_add(self.channel_map),
      None => None,
    }
  }

  /// The same total with `extradata` left out — what a clone retains
  /// when the caller is going to strip it.
  ///
  /// The synthesized-attachment road does exactly that: a font's
  /// extradata *is* its payload, the carrier already holds it, and
  /// counting it twice would make the budget describe the file rather
  /// than the memory.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn total_without_extradata(&self) -> Option<usize> {
    self.coded_side_data.checked_add(self.channel_map)
  }
}

/// `AVCodecParameters` has thirty-three fields in FFmpeg n9.0 and
/// exactly three of them reach the heap. This tripwire fires if the
/// struct changes shape, because [`measure_parameters`] and
/// [`bounded_clone_parameters`] enumerate those three **by hand** and a
/// fourth would silently go uncounted and uncopied.
///
/// A size assertion is a tripwire, not a proof: it catches a struct
/// that grew or was reordered, which is how a new heap seat arrives in
/// practice. Gated to 64-bit because the number is pointer-width
/// dependent and every target this crate links FFmpeg on is 64-bit;
/// elsewhere the hand-written clone still runs, it just loses the
/// alarm.
#[cfg(target_pointer_width = "64")]
const _: () = {
  assert!(
    core::mem::size_of::<ffmpeg_next::ffi::AVCodecParameters>() == 184,
    "AVCodecParameters changed shape — re-census its heap fields against \
     `measure_parameters` and `bounded_clone_parameters` before raising this",
  );
};

/// Measures an `AVCodecParameters`' heap seats without allocating
/// anything.
///
/// `None` when a declared size cannot be added up — a count or length
/// whose arithmetic overflows is malformed, and refusing beats
/// saturating into a number that then passes a budget.
///
/// # Safety
///
/// `par` must be a live `*const AVCodecParameters` for the duration of
/// this call.
pub(crate) unsafe fn measure_parameters(
  par: *const ffmpeg_next::ffi::AVCodecParameters,
) -> Option<ParameterFootprint> {
  // SAFETY: `par` is live per the contract; `extradata` and
  // `extradata_size` are a pointer and an integer.
  let extradata_payload = if unsafe { (*par).extradata }.is_null() {
    0
  } else {
    usize::try_from(unsafe { (*par).extradata_size }).ok()?
  };
  // The padding a *clone* allocates is part of what a clone costs. A
  // carrier of the same bytes allocates only the payload, which is why
  // both numbers are kept.
  let extradata = if extradata_payload == 0 {
    0
  } else {
    extradata_payload.checked_add(ffmpeg_next::ffi::AV_INPUT_BUFFER_PADDING_SIZE as usize)?
  };

  let side_data_ptr = unsafe { (*par).coded_side_data };
  let side_data_count = unsafe { (*par).nb_coded_side_data };
  let coded_side_data = if side_data_ptr.is_null() || side_data_count <= 0 {
    0
  } else {
    let count = usize::try_from(side_data_count).ok()?;
    let mut total = count.checked_mul(core::mem::size_of::<ffmpeg_next::ffi::AVPacketSideData>())?;
    for index in 0..count {
      // **Never `&*entry`.** `AVPacketSideData` carries a `type` field
      // of an *open* C enum: FFmpeg adds side-data kinds between
      // releases, and an ABI-compatible library newer than the
      // bindings this crate was built against will emit values absent
      // from the generated Rust enum. Forming a typed reference to such
      // a struct asserts every field inhabits its declared type, which
      // is undefined behaviour before a single field is read. Only the
      // `size` field is needed here, and it is reached through
      // `addr_of!` and read as the plain `usize` it is.
      //
      // SAFETY: the array is valid for `nb_coded_side_data` contiguous
      // entries per FFmpeg's contract, `index` is below that count, and
      // `addr_of!` computes a field address without forming a reference
      // to the struct that contains it.
      let size =
        unsafe { core::ptr::read_unaligned(core::ptr::addr_of!((*side_data_ptr.add(index)).size)) };
      total = total.checked_add(size)?;
    }
    total
  };

  let channel_map = {
    // The channel order is an open enum too, and this one decides
    // whether the layout owns a heap allocation at all. Read as the
    // integer it is on the wire and compared against the orders whose
    // heap semantics this crate has censused; anything else **fails
    // closed**, because a future order might own memory nobody here
    // knows how to measure and guessing zero would admit it unbudgeted.
    //
    // SAFETY: `ch_layout` is embedded by value; `addr_of!` reaches
    // `order` without forming a reference to the layout, and the field
    // has the layout of a `c_int`.
    let order = unsafe {
      core::ptr::read_unaligned(core::ptr::addr_of!((*par).ch_layout.order).cast::<i32>())
    };
    const UNSPEC: i32 = ffmpeg_next::ffi::AVChannelOrder::AV_CHANNEL_ORDER_UNSPEC as i32;
    const NATIVE: i32 = ffmpeg_next::ffi::AVChannelOrder::AV_CHANNEL_ORDER_NATIVE as i32;
    const CUSTOM: i32 = ffmpeg_next::ffi::AVChannelOrder::AV_CHANNEL_ORDER_CUSTOM as i32;
    const AMBISONIC: i32 = ffmpeg_next::ffi::AVChannelOrder::AV_CHANNEL_ORDER_AMBISONIC as i32;
    match order {
      // These three describe their channels with the union's `mask`
      // arm, which owns nothing.
      UNSPEC | NATIVE | AMBISONIC => 0,
      // Only this one owns a heap map.
      CUSTOM => {
        let channels = usize::try_from(unsafe { (*par).ch_layout.nb_channels }).ok()?;
        channels.checked_mul(core::mem::size_of::<ffmpeg_next::ffi::AVChannelCustom>())?
      }
      // An order this build has never heard of. Refusing is the only
      // honest answer: its union arm is unknown, so both "it owns
      // nothing" and "it owns `nb_channels` of something" are guesses.
      _ => return None,
    }
  };

  Some(ParameterFootprint {
    extradata,
    extradata_payload,
    coded_side_data,
    channel_map,
  })
}

/// Whether a parameter clone carries `extradata` across.
///
/// The synthesized-attachment road omits it: a font's `extradata`
/// **is** the attachment payload, the carrier already holds it, and a
/// second copy is residency nobody asked for.
///
/// **Omitted from the outset, never stripped afterwards.** Stripping
/// was the shape that shipped first and it was wrong twice over: the
/// bytes were allocated before being freed, and — worse — the clone
/// measured and charged them against the *parameter* ceiling on the
/// way past. A payload sitting between the two ceilings (over the
/// 16 MiB parameter one, under the 64 MiB attachment one) therefore
/// passed the session's admission and then failed deterministically
/// inside the clone, refusing a file the budgets had already agreed to
/// open. Omitting from the outset makes the clone's accounting the
/// same accounting the admission did.
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash)]
pub(crate) enum ExtradataPolicy {
  /// Copy `extradata` across — every road but one.
  #[default]
  Copy,
  /// Leave `extradata` behind: never allocated, never charged.
  Omit,
}

/// The `ENOMEM` a heap seat's copy reports when its allocation fails.
///
/// [`DemuxError::ParametersAlloc`] names the *destination struct*
/// failing to allocate; a seat that fails after that is the copy
/// failing part way, which is what
/// [`DemuxError::ParametersCopy`] was minted for and what
/// `avcodec_parameters_copy` itself would have returned here.
fn seat_copy_failed(stream_index: usize) -> DemuxError {
  DemuxError::ParametersCopy(ParametersCopy::new(
    stream_index,
    ffmpeg_next::Error::Other {
      errno: libc::ENOMEM,
    },
  ))
}

/// A deep copy of codec parameters in which **every heap field passes a
/// budget before it is copied**.
///
/// # The rule this exists to enforce
///
/// > **No code path in this crate hands attacker-sized parameter data
/// > to a wholesale FFI copy.**
///
/// `avcodec_parameters_copy` is that wholesale copy, and it was the
/// same defect three review rounds running. It deep-copies every heap
/// field an `AVCodecParameters` has — `extradata`, every
/// `coded_side_data` entry, a custom channel map — and it does so
/// before anything has asked how big they are. The first two rounds
/// patched the field that had been noticed; the third found another
/// (`coded_side_data`, where a MOV `prof` atom puts an ICC profile),
/// which is the signal that patching fields is not a fix. So the
/// wholesale copy is gone from every attacker-facing path and this
/// function replaces it.
///
/// The shape that makes the class unable to recur: the heap seats are
/// enumerated **by hand**, each is measured before it is copied, and
/// the whole footprint is admitted against a budget first. A field
/// nobody enumerated is a field that is not copied — which loses data
/// rather than allocating it — and the compile-time size tripwire above
/// fires when one appears.
///
/// # What it copies
///
/// Every scalar, by a bytewise copy of the struct — so a *scalar* field
/// a future FFmpeg adds travels for free. Then the three heap seats are
/// nulled on the destination (the bytewise copy left them aliasing the
/// source) and rebuilt one at a time:
///
/// 1. `extradata`, with the `AV_INPUT_BUFFER_PADDING_SIZE` trailing
///    zeroes decoders read past the end into;
/// 2. `coded_side_data` — the descriptor array, then each entry's
///    payload;
/// 3. `ch_layout`, through `av_channel_layout_copy`, whose one
///    allocation is the custom map this function has already measured.
///
/// Nothing a decoder consumes is dropped: the SPS/PPS in `extradata`,
/// the side data codecs read, and the channel layout all survive, which
/// is what the decode, resample and image suites prove by continuing to
/// pass unchanged.
pub(crate) fn bounded_clone_parameters(
  source: &Parameters,
  stream_index: usize,
  budget: usize,
) -> Result<Parameters, DemuxError> {
  bounded_clone_parameters_with(source, stream_index, budget, ExtradataPolicy::Copy)
}

/// [`bounded_clone_parameters`], with the `extradata` policy named.
pub(crate) fn bounded_clone_parameters_with(
  source: &Parameters,
  stream_index: usize,
  budget: usize,
  extradata_policy: ExtradataPolicy,
) -> Result<Parameters, DemuxError> {
  // The *source* first. `Parameters::new()` and `Parameters::default()`
  // hand back a value whose pointer is null when
  // `avcodec_parameters_alloc` failed — safe code, no error, no way to
  // tell — and every read below dereferences it.
  // SAFETY: reading the pointer without dereferencing it.
  let src = unsafe { source.as_ptr() };
  if src.is_null() {
    return Err(DemuxError::ParametersMissing(ParametersMissing::new(
      stream_index,
    )));
  }

  // SAFETY: `src` is a live `AVCodecParameters` owned by `source` for
  // the duration of this call.
  let footprint = unsafe { measure_parameters(src) }.ok_or_else(|| {
    DemuxError::ParametersTooLarge(ParametersTooLarge::new(stream_index, usize::MAX, budget))
  })?;
  // Charged for what this clone will actually retain, which is what
  // the session's admission pass charged for too — see
  // [`ExtradataPolicy`] for the interval that disagreeing about this
  // used to lose.
  let total = match extradata_policy {
    ExtradataPolicy::Copy => footprint.total(),
    ExtradataPolicy::Omit => footprint.total_without_extradata(),
  }
  .ok_or_else(|| {
    DemuxError::ParametersTooLarge(ParametersTooLarge::new(stream_index, usize::MAX, budget))
  })?;
  if total > budget {
    return Err(DemuxError::ParametersTooLarge(ParametersTooLarge::new(
      stream_index,
      total,
      budget,
    )));
  }

  let mut out = Parameters::new();
  // SAFETY: reading the pointer the constructor stored without
  // dereferencing it — which is exactly what the check is for.
  let dst = unsafe { out.as_mut_ptr() };
  if dst.is_null() {
    return Err(DemuxError::ParametersAlloc(ParametersAlloc::new(
      stream_index,
    )));
  }

  // SAFETY: `src` and `dst` are both live, non-null, distinct
  // `AVCodecParameters` allocations. The bytewise copy carries every
  // scalar across — including any this crate has never heard of — and
  // leaves the three pointer seats aliasing `src`, which the very next
  // statements overwrite before anything can observe or free them.
  unsafe {
    core::ptr::copy_nonoverlapping(src, dst, 1);
    (*dst).extradata = core::ptr::null_mut();
    (*dst).extradata_size = 0;
    (*dst).coded_side_data = core::ptr::null_mut();
    (*dst).nb_coded_side_data = 0;
    // `ch_layout` is zeroed rather than nulled field-by-field:
    // `AV_CHANNEL_ORDER_UNSPEC` is `0`, so an all-zero layout is the
    // valid "nothing here yet" state `av_channel_layout_copy` expects
    // to be handed, and it owns no map.
    (*dst).ch_layout = core::mem::zeroed();
  }

  // 1. extradata, with the padding decoders read into — unless the
  // caller asked for it to be left behind, in which case nothing is
  // allocated and the destination keeps the null the cleanup above put
  // there. `footprint.extradata()` already counts that padding.
  if footprint.extradata() > 0 && matches!(extradata_policy, ExtradataPolicy::Copy) {
    let padded = footprint.extradata();
    // SAFETY: `av_mallocz` returns zeroed memory or null; the copy
    // writes exactly the measured length into an allocation that is
    // `AV_INPUT_BUFFER_PADDING_SIZE` longer, leaving the padding zero.
    unsafe {
      let buffer = ffmpeg_next::ffi::av_mallocz(padded) as *mut u8;
      if buffer.is_null() {
        return Err(seat_copy_failed(stream_index));
      }
      let payload =
        usize::try_from((*src).extradata_size).map_err(|_| seat_copy_failed(stream_index))?;
      core::ptr::copy_nonoverlapping((*src).extradata, buffer, payload);
      (*dst).extradata = buffer;
      (*dst).extradata_size = (*src).extradata_size;
    }
  }

  // 2. coded_side_data — the descriptor array, then each payload.
  //
  // SAFETY: the count and array were measured above; every entry is
  // read within the declared count, and each payload is copied at the
  // length its own descriptor declares.
  unsafe {
    let count = (*src).nb_coded_side_data;
    if count > 0 && !(*src).coded_side_data.is_null() {
      let entries = usize::try_from(count)
        .ok()
        .and_then(|c| c.checked_mul(core::mem::size_of::<ffmpeg_next::ffi::AVPacketSideData>()))
        .ok_or_else(|| seat_copy_failed(stream_index))?;
      let array = ffmpeg_next::ffi::av_mallocz(entries) as *mut ffmpeg_next::ffi::AVPacketSideData;
      if array.is_null() {
        return Err(seat_copy_failed(stream_index));
      }
      // Attached before the payloads are filled in, so a failure part
      // way leaves `out`'s own destructor a well-formed array to walk:
      // the entries it has not reached are zeroed, and freeing a null
      // payload is a no-op.
      (*dst).coded_side_data = array;
      (*dst).nb_coded_side_data = count;
      for index in 0..count as usize {
        // Field pointers, never `&AVPacketSideData` — the `type` field
        // is an open C enum and a newer-but-ABI-compatible FFmpeg emits
        // kinds these bindings do not name. See `measure_parameters`
        // for the whole argument.
        let from = (*src).coded_side_data.add(index);
        let into = array.add(index);
        // The type id travels as the **raw bits it is on the wire**.
        // Reading it as the Rust enum would be the very UB this avoids,
        // and a kind this build cannot name is still a kind the file
        // carries and a decoder may want.
        let kind = core::ptr::read_unaligned(core::ptr::addr_of!((*from).type_).cast::<i32>());
        core::ptr::write_unaligned(core::ptr::addr_of_mut!((*into).type_).cast::<i32>(), kind);

        let size = core::ptr::read_unaligned(core::ptr::addr_of!((*from).size));
        let data = core::ptr::read_unaligned(core::ptr::addr_of!((*from).data));
        if size > 0 && !data.is_null() {
          let payload = ffmpeg_next::ffi::av_mallocz(size) as *mut u8;
          if payload.is_null() {
            return Err(seat_copy_failed(stream_index));
          }
          core::ptr::copy_nonoverlapping(data, payload, size);
          core::ptr::write_unaligned(core::ptr::addr_of_mut!((*into).data), payload);
          core::ptr::write_unaligned(core::ptr::addr_of_mut!((*into).size), size);
        } else {
          core::ptr::write_unaligned(core::ptr::addr_of_mut!((*into).size), 0);
        }
      }
    }
  }

  // 3. ch_layout. One FFmpeg call, over one field whose only allocation
  // is the custom map this function measured and admitted above.
  //
  // SAFETY: both layouts are live; the destination is the zeroed
  // (`AV_CHANNEL_ORDER_UNSPEC`) state this function put it in, which is
  // what `av_channel_layout_copy` requires of a destination it may
  // overwrite.
  let rc = unsafe {
    ffmpeg_next::ffi::av_channel_layout_copy(
      core::ptr::addr_of_mut!((*dst).ch_layout),
      core::ptr::addr_of!((*src).ch_layout),
    )
  };
  if rc < 0 {
    return Err(DemuxError::ParametersCopy(ParametersCopy::new(
      stream_index,
      ffmpeg_next::Error::from(rc),
    )));
  }

  Ok(out)
}

/// Per-`TrackInfo` extras — the FFmpeg side of one track-table row.
///
/// Carries the stream's [`Parameters`], which is what opens a decoder
/// for the track — through [`Self::clone_parameters`], which is a deep
/// `avcodec_parameters_copy` with no tie back to the format context, so
/// a decoder outlives the demuxer that named it.
///
/// **No `Clone`, and no `Default`.** Both would have to go through
/// `ffmpeg_next`'s `Clone` / `Default` for [`Parameters`], which check
/// neither the allocation nor the copy: safe public code could
/// dereference a null destination or receive parameters that are
/// quietly incomplete. `Clone` cannot report either, so this type does
/// not implement it; [`Self::try_clone`] is the same copy with the
/// answer a caller can act on, and [`Self::clone_parameters`] is the
/// handoff a decoder actually needs. This crate shipped a derived
/// `Clone` over the unchecked path once, reachable from safe code
/// that just copied a track row, and closed it by removing the
/// derive (see
/// `demuxer::tests::the_public_track_extra_copies_are_checked_too`).
///
/// The message-carrier law is the second, independent reason `Clone`
/// stays off: messages may be `Clone`, but `Clone` is always a
/// refcount bump, never a deep copy, and `avcodec_parameters_copy` is
/// not that. This crate shipped a *hand-written*, checked `Clone`
/// here once too — through [`Self::try_clone`], to satisfy a channel
/// bound — and it came back out for the same reason: a consumer that
/// needs to share the [`TrackInfo`](mediadecode::demuxer::TrackInfo)
/// this type lives inside wraps it in `Arc` once, at the door,
/// instead of paying a deep copy per consumer. [`Self::try_clone`]
/// remains for the one caller that genuinely wants an owned duplicate
/// of the codec parameters, which sharing a message is not.
///
/// `disposition` is the raw `AV_DISPOSITION_*` bit set, not
/// `ffmpeg_next::format::stream::Disposition`. That type's
/// `from_bits_truncate` drops bits the linked build has no constant
/// for, and this crate's stance on bit sets is that every pattern is a
/// value — the same reason `PacketFlags` reaches the wire as a number.
pub struct TrackExtra {
  stream_index: i32,
  disposition: i32,
  start_time: Option<i64>,
  frame_count: Option<i64>,
  parameters: Parameters,
  /// The measured heap size of [`Self::parameters`] — see
  /// [`Self::parameter_bytes`].
  parameter_bytes: usize,
}

impl TrackExtra {
  /// Constructs a `TrackExtra` from the stream index and its codec
  /// parameters. Everything else starts absent.
  ///
  /// **Fallible, and that is the point.** `Parameters::new()` and
  /// `Parameters::default()` are safe constructors that hand back a
  /// null-backed value when `avcodec_parameters_alloc` fails, saying
  /// nothing; accepting one here would store a landmine that goes off
  /// later, in a copy, on a thread that has forgotten the allocator
  /// ever failed. Refusing it at the door is what lets every other
  /// method on this type — and every reader of
  /// [`Self::parameters`] — rely on there being parameters at all.
  ///
  /// Not `const fn`: [`Parameters`] owns a heap allocation.
  pub fn new(stream_index: i32, parameters: Parameters) -> Result<Self, DemuxError> {
    // SAFETY: reading the pointer without dereferencing it.
    let par = unsafe { parameters.as_ptr() };
    if par.is_null() {
      return Err(DemuxError::ParametersMissing(ParametersMissing::new(
        stream_index.max(0) as usize,
      )));
    }
    // The heap size of what this row is about to hold, measured once.
    // It is the budget every later re-clone is judged against: those
    // copy *these* parameters, which have already been admitted, so the
    // honest ceiling for them is exactly what they were admitted at —
    // no policy to consult, and a copy that somehow grew is refused
    // rather than silently paid for.
    //
    // SAFETY: `par` is a live `AVCodecParameters` owned by
    // `parameters`; the measurement allocates nothing and dereferences
    // only what it counts.
    let parameter_bytes = unsafe { measure_parameters(par) }
      .and_then(|footprint| footprint.total())
      .ok_or_else(|| {
        DemuxError::ParametersTooLarge(ParametersTooLarge::new(
          stream_index.max(0) as usize,
          usize::MAX,
          usize::MAX,
        ))
      })?;
    Ok(Self {
      stream_index,
      disposition: 0,
      start_time: None,
      frame_count: None,
      parameters,
      parameter_bytes,
    })
  }

  /// The heap bytes this row's codec parameters hold — `extradata`,
  /// `coded_side_data` and a custom channel map together.
  ///
  /// The number the session admitted at open, and the ceiling every
  /// copy [`Self::clone_parameters`] hands out is judged against.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn parameter_bytes(&self) -> usize {
    self.parameter_bytes
  }

  /// A deep copy of this row, with the codec-parameter copy checked.
  ///
  /// The fallible counterpart of the `Clone` this type deliberately
  /// does not implement — see the type's own documentation for why.
  pub fn try_clone(&self) -> Result<Self, DemuxError> {
    // No re-check: `self` cannot exist over null-backed parameters, and
    // `clone_parameters` never returns one.
    Ok(Self {
      stream_index: self.stream_index,
      disposition: self.disposition,
      start_time: self.start_time,
      frame_count: self.frame_count,
      parameters: self.clone_parameters()?,
      parameter_bytes: self.parameter_bytes,
    })
  }

  /// An owned deep copy of the track's codec parameters — the handoff
  /// that opens a decoder for this track.
  ///
  /// `FfmpegAudioStreamDecoder::open(track.extra().clone_parameters()?,
  /// track.timebase())`. Fallible because the copy is: an allocation
  /// failure here is the difference between a decoder that is not
  /// opened and one opened on parameters that are not the file's.
  pub fn clone_parameters(&self) -> Result<Parameters, DemuxError> {
    // Through the bounded clone, like every other parameter copy in
    // this crate — see [`bounded_clone_parameters`] for the rule. The
    // budget is this row's own admitted footprint: these parameters
    // passed the session's ceiling at open, so a copy of them that
    // needs more than they hold is a bug rather than a policy question.
    bounded_clone_parameters(
      &self.parameters,
      self.stream_index.max(0) as usize,
      self.parameter_bytes,
    )
  }

  /// Returns the source `AVStream.index`.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn stream_index(&self) -> i32 {
    self.stream_index
  }
  /// Returns the raw `AVStream.disposition` bit set.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn disposition(&self) -> i32 {
    self.disposition
  }
  /// Returns the stream's start time in the track's timebase, or
  /// `None` when the container does not carry one.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn start_time(&self) -> Option<i64> {
    self.start_time
  }
  /// Returns `AVStream.nb_frames` when the container carries it.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn frame_count(&self) -> Option<i64> {
    self.frame_count
  }
  /// Returns the stream's codec parameters — the handle a decoder is
  /// opened from.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn parameters(&self) -> &Parameters {
    &self.parameters
  }

  /// Sets the disposition bits (consuming builder).
  #[cfg_attr(not(tarpaulin), inline(always))]
  #[must_use]
  pub const fn with_disposition(mut self, value: i32) -> Self {
    self.disposition = value;
    self
  }
  /// Sets the start time (consuming builder).
  #[cfg_attr(not(tarpaulin), inline(always))]
  #[must_use]
  pub const fn with_start_time(mut self, value: Option<i64>) -> Self {
    self.start_time = value;
    self
  }
  /// Sets the frame count (consuming builder).
  #[cfg_attr(not(tarpaulin), inline(always))]
  #[must_use]
  pub const fn with_frame_count(mut self, value: Option<i64>) -> Self {
    self.frame_count = value;
    self
  }

  /// Sets the disposition bits in place.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn set_disposition(&mut self, value: i32) -> &mut Self {
    self.disposition = value;
    self
  }
  /// Sets the start time in place.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn set_start_time(&mut self, value: Option<i64>) -> &mut Self {
    self.start_time = value;
    self
  }
  /// Sets the frame count in place.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn set_frame_count(&mut self, value: Option<i64>) -> &mut Self {
    self.frame_count = value;
    self
  }
}

impl std::fmt::Debug for TrackExtra {
  /// Hand-written because [`Parameters`] does not derive `Debug`. The
  /// medium and codec id are the two fields worth printing; the rest of
  /// `AVCodecParameters` is per-kind detail the track row already
  /// carries in typed form.
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    f.debug_struct("TrackExtra")
      .field("stream_index", &self.stream_index)
      .field("disposition", &format_args!("{:#x}", self.disposition))
      .field("start_time", &self.start_time)
      .field("frame_count", &self.frame_count)
      .field(
        "parameters",
        &format_args!("{:?}", crate::boundary::media_kind_of(&self.parameters)),
      )
      .finish()
  }
}

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

  #[test]
  fn defaults_construct() {
    let v = VideoPacketExtra::default();
    assert_eq!(v.stream_index(), 0);
    assert!(v.side_data().is_empty());

    let f = VideoFrameExtra::default();
    assert_eq!(f.picture_type(), PictureType::Unspecified);
    assert!(!f.key_frame());
    assert!(f.mastering_display().is_none());

    let s = SubtitleFrameExtra::default();
    assert_eq!(s.start_display_time(), 0);
    assert_eq!(s.end_display_time(), 0);
  }

  #[test]
  fn picture_type_default_is_unspecified() {
    assert_eq!(PictureType::default(), PictureType::Unspecified);
  }

  /// Builds an `AVCodecParameters` with the heap seats a file
  /// controls, so the preflight and the bounded clone can be driven
  /// without a container.
  ///
  /// The same discipline as the EXIF fixture: a shape the `ffmpeg` CLI
  /// cannot mint is built here, by hand, beside the assertions it
  /// feeds. A MOV `prof` atom lands in `coded_side_data` as an
  /// `AV_PKT_DATA_ICC_PROFILE` entry — that is the road this
  /// constructs, at whatever size the test asks for.
  fn parameters_with(extradata: usize, icc_profile: usize) -> Parameters {
    let mut out = Parameters::new();
    // SAFETY: `out` owns a live `AVCodecParameters`. Every buffer below
    // comes from FFmpeg's allocator and is handed to it, so
    // `avcodec_parameters_free` releases all of them with the struct.
    unsafe {
      let par = out.as_mut_ptr();
      if extradata > 0 {
        let buffer = ffmpeg_next::ffi::av_mallocz(extradata) as *mut u8;
        assert!(!buffer.is_null(), "av_mallocz extradata");
        (*par).extradata = buffer;
        (*par).extradata_size = extradata as i32;
      }
      if icc_profile > 0 {
        let array = ffmpeg_next::ffi::av_mallocz(core::mem::size_of::<
          ffmpeg_next::ffi::AVPacketSideData,
        >()) as *mut ffmpeg_next::ffi::AVPacketSideData;
        assert!(!array.is_null(), "av_mallocz side-data array");
        let payload = ffmpeg_next::ffi::av_mallocz(icc_profile) as *mut u8;
        assert!(!payload.is_null(), "av_mallocz icc profile");
        (*array).data = payload;
        (*array).size = icc_profile;
        (*array).type_ = ffmpeg_next::ffi::AVPacketSideDataType::AV_PKT_DATA_ICC_PROFILE;
        (*par).coded_side_data = array;
        (*par).nb_coded_side_data = 1;
      }
    }
    out
  }

  fn footprint_of(parameters: &Parameters) -> ParameterFootprint {
    // SAFETY: `parameters` owns a live `AVCodecParameters`.
    unsafe { measure_parameters(parameters.as_ptr()) }.expect("measurable")
  }

  #[test]
  fn the_measurement_counts_every_heap_seat_and_allocates_nothing() {
    // The inventory the bounded clone is written against: `extradata`,
    // `coded_side_data` (payload *and* descriptor array), and a custom
    // channel map. A seat the measurement misses is a seat the budget
    // never sees, which is how this class kept coming back.
    const PAD: usize = ffmpeg_next::ffi::AV_INPUT_BUFFER_PADDING_SIZE as usize;
    const DESCRIPTOR: usize = core::mem::size_of::<ffmpeg_next::ffi::AVPacketSideData>();
    let parameters = parameters_with(4_096, 64 * 1024);
    let footprint = footprint_of(&parameters);
    // The padding a copy allocates is part of what a copy costs: a
    // ceiling that counted only the payload admitted an allocation
    // `AV_INPUT_BUFFER_PADDING_SIZE` larger than it agreed to.
    assert_eq!(footprint.extradata(), 4_096 + PAD);
    assert_eq!(
      footprint.coded_side_data(),
      64 * 1024 + DESCRIPTOR,
      "the descriptor array is an allocation too",
    );
    assert_eq!(footprint.channel_map(), 0, "no custom layout here");
    assert_eq!(
      footprint.total(),
      Some(4_096 + PAD + 64 * 1024 + DESCRIPTOR),
    );
    // The omit-aware total leaves extradata *and its padding* out,
    // which is what keeps a synthesized attachment from being charged
    // for bytes the clone never allocates.
    assert_eq!(
      footprint.total_without_extradata(),
      Some(64 * 1024 + DESCRIPTOR),
    );
    // And no extradata at all means no padding either.
    assert_eq!(footprint_of(&parameters_with(0, 8)).extradata(), 0);
  }

  #[test]
  fn an_oversized_coded_side_data_entry_is_refused_before_the_clone() {
    // The R3 finding, at unit level: `avcodec_parameters_copy` deep-copies
    // every `coded_side_data` entry, and a MOV `prof` atom is where an
    // attacker-sized one arrives. The bounded clone measures first.
    let parameters = parameters_with(0, 8 * 1024 * 1024);
    let declared = footprint_of(&parameters).total().expect("measurable");

    match bounded_clone_parameters(&parameters, 3, 64 * 1024) {
      Err(DemuxError::ParametersTooLarge(p)) => {
        assert_eq!(p.stream_index(), 3);
        assert_eq!(p.bytes(), declared);
        assert_eq!(p.limit(), 64 * 1024);
      }
      Err(other) => panic!("expected ParametersTooLarge, got {other:?}"),
      Ok(_) => panic!("an 8 MiB ICC profile passed a 64 KiB ceiling"),
    }

    // Exactly at the line is not over it, and the copy is faithful.
    let cloned =
      bounded_clone_parameters(&parameters, 3, declared).expect("at the cap is not over it");
    assert_eq!(footprint_of(&cloned), footprint_of(&parameters));
  }

  #[test]
  fn a_legitimate_multi_megabyte_icc_profile_is_admitted_by_default() {
    // The honest end of the range this budget has to clear: a real
    // camera or display ICC profile. A ceiling that refused these would
    // be a ceiling nobody could ship behind.
    let parameters = parameters_with(1_024, 4 * 1024 * 1024);
    let cloned = bounded_clone_parameters(
      &parameters,
      0,
      crate::limits::DEFAULT_MAX_CODEC_PARAMETER_BYTES,
    )
    .expect("a 4 MiB ICC profile is real media");
    // And it arrived whole — a clone that silently dropped the profile
    // would pass a size assertion and fail a consumer.
    assert_eq!(footprint_of(&cloned), footprint_of(&parameters));
  }

  #[test]
  fn the_bounded_clone_keeps_every_field_a_decoder_consumes() {
    // Decode-capability parity, asserted directly as well as by the
    // decode suites passing unchanged: scalars, extradata bytes (with
    // the padding decoders read into), and each side-data entry's type
    // and payload all survive.
    let parameters = parameters_with(32, 128);
    // SAFETY: `parameters` owns a live `AVCodecParameters`; the writes
    // below are plain scalar fields.
    unsafe {
      let par = parameters.as_ptr() as *mut ffmpeg_next::ffi::AVCodecParameters;
      (*par).codec_id = ffmpeg_next::ffi::AVCodecID::AV_CODEC_ID_H264;
      (*par).width = 1920;
      (*par).height = 1080;
      (*par).bit_rate = 5_000_000;
      (*par).sample_rate = 48_000;
      core::ptr::write_bytes((*par).extradata, 0xAB, 32);
      core::ptr::write_bytes((*(*par).coded_side_data).data, 0xCD, 128);
    }

    let cloned = bounded_clone_parameters(&parameters, 0, usize::MAX).expect("clone");
    // SAFETY: both own live `AVCodecParameters`.
    unsafe {
      let src = parameters.as_ptr();
      let dst = cloned.as_ptr();
      assert_eq!((*dst).codec_id, (*src).codec_id, "the scalar sweep");
      assert_eq!(((*dst).width, (*dst).height), (1920, 1080));
      assert_eq!((*dst).bit_rate, 5_000_000);
      assert_eq!((*dst).sample_rate, 48_000);

      assert_eq!((*dst).extradata_size, 32);
      assert_ne!(
        (*dst).extradata,
        (*src).extradata,
        "it is a copy, not an alias"
      );
      let extradata = core::slice::from_raw_parts((*dst).extradata, 32);
      assert!(extradata.iter().all(|&b| b == 0xAB), "SPS/PPS survived");
      // The padding a decoder reads past the end into is present and
      // zeroed — `avcodec_parameters_copy` guarantees it and so must we.
      let padded = core::slice::from_raw_parts(
        (*dst).extradata.add(32),
        ffmpeg_next::ffi::AV_INPUT_BUFFER_PADDING_SIZE as usize,
      );
      assert!(padded.iter().all(|&b| b == 0), "the read-past padding");

      assert_eq!((*dst).nb_coded_side_data, 1);
      let entry = &*(*dst).coded_side_data;
      assert_eq!(entry.size, 128);
      assert_eq!(
        entry.type_,
        ffmpeg_next::ffi::AVPacketSideDataType::AV_PKT_DATA_ICC_PROFILE,
      );
      assert_ne!(entry.data, (*(*src).coded_side_data).data, "a copy");
      let payload = core::slice::from_raw_parts(entry.data, 128);
      assert!(
        payload.iter().all(|&b| b == 0xCD),
        "the ICC profile survived"
      );
    }
  }

  #[test]
  fn side_data_entry_carries_bytes() {
    let entry = SideDataEntry::new(12345, FfmpegBytes::copy_from_slice(&[1, 2, 3, 4]));
    assert_eq!(entry.kind(), 12345);
    assert_eq!(entry.data(), &[1, 2, 3, 4]);
  }

  #[test]
  fn side_data_entry_clone_shares_its_payload() {
    // The amputation contract's consumer-side half, one tier in: a
    // frame's metadata clones as cheaply as its pixels do.
    let entry = SideDataEntry::new(7, FfmpegBytes::copy_from_slice(&[9u8; 64]));
    let cloned = entry.clone();
    assert!(
      entry.data_ref().ptr_eq(cloned.data_ref()),
      "cloning a side-data entry copied its bytes",
    );
    assert_eq!(cloned.data(), entry.data());
  }

  /// The eight matrices, exactly as this build of libavcodec emits
  /// them — measured by feeding mjpeg a JPEG whose EXIF IFD carries
  /// each tag in turn, then reading the frame's
  /// `AV_FRAME_DATA_DISPLAYMATRIX` entry back.
  const MEASURED: [(u16, ImageOrientation, [i32; 4]); 8] = [
    (1, ImageOrientation::TopLeft, [65536, 0, 0, 65536]),
    (2, ImageOrientation::TopRight, [-65536, 0, 0, 65536]),
    (3, ImageOrientation::BottomRight, [-65536, 0, 0, -65536]),
    (4, ImageOrientation::BottomLeft, [65536, 0, 0, -65536]),
    (5, ImageOrientation::LeftTop, [0, 65536, 65536, 0]),
    (6, ImageOrientation::RightTop, [0, 65536, -65536, 0]),
    (7, ImageOrientation::RightBottom, [0, -65536, -65536, 0]),
    (8, ImageOrientation::LeftBottom, [0, -65536, 65536, 0]),
  ];

  /// A full nine-word display matrix with `linear` in the four
  /// load-bearing slots and canonical values everywhere else, laid out
  /// as `libavutil/display.h` specifies and in native byte order, as
  /// the side data really is.
  fn display_matrix(linear: [i32; 4]) -> Vec<u8> {
    words_to_bytes([
      linear[0],
      linear[1],
      0,
      linear[2],
      linear[3],
      0,
      0,
      0,
      1 << 30,
    ])
  }

  fn words_to_bytes(words: [i32; 9]) -> Vec<u8> {
    words.iter().flat_map(|w| w.to_ne_bytes()).collect()
  }

  #[test]
  fn every_measured_display_matrix_reads_back_as_its_exif_tag() {
    for (tag, expected, linear) in MEASURED {
      let read = ImageOrientation::from_display_matrix(&display_matrix(linear))
        .expect("a nine-word matrix is readable");
      assert_eq!(read, expected, "tag {tag}");
      assert_eq!(read.to_exif_code(), Some(tag));
      assert_eq!(ImageOrientation::from_exif_code(tag), Some(read));
      // The inverse: the variant knows the matrix it came from.
      assert_eq!(read.linear(), linear, "tag {tag}");
    }
  }

  #[test]
  fn the_four_mirrored_tags_are_the_ones_exif_says_they_are() {
    // 2, 4, 5, 7 — and this is exactly the half `av_display_rotation_get`
    // cannot distinguish, which is why the seat is eight-valued.
    for (tag, orientation, _) in MEASURED {
      assert_eq!(
        orientation.is_mirrored(),
        matches!(tag, 2 | 4 | 5 | 7),
        "tag {tag}",
      );
    }
  }

  #[test]
  fn the_quarter_turn_lands_in_the_workspace_rotation_vocabulary() {
    use ImageOrientation::*;
    assert_eq!(TopLeft.rotation(), Some(Rotation::D0));
    assert_eq!(TopRight.rotation(), Some(Rotation::D0));
    assert_eq!(RightTop.rotation(), Some(Rotation::D90));
    assert_eq!(LeftTop.rotation(), Some(Rotation::D90));
    assert_eq!(BottomRight.rotation(), Some(Rotation::D180));
    assert_eq!(BottomLeft.rotation(), Some(Rotation::D180));
    assert_eq!(LeftBottom.rotation(), Some(Rotation::D270));
    assert_eq!(RightBottom.rotation(), Some(Rotation::D270));
    // Four rotations, eight orientations: the rotation alone cannot
    // tell 1 from 2, which is the whole reason this type exists.
    assert_eq!(TopLeft.rotation(), TopRight.rotation());
    assert_ne!(TopLeft, TopRight);
  }

  #[test]
  fn a_transform_the_vocabulary_cannot_name_is_carried_not_collapsed() {
    // An arbitrary affine linear part — a MOV `tkhd` can carry one.
    // Answering `TopLeft` here is the silent loss this crate refuses.
    let odd = [46_341, 46_341, -46_341, 46_341]; // ~45 degrees
    let words: [i32; 9] = [odd[0], odd[1], 0, odd[2], odd[3], 0, 0, 0, 1 << 30];
    let read =
      ImageOrientation::from_display_matrix(&display_matrix(odd)).expect("readable, just unnamed");
    assert_eq!(read, ImageOrientation::Other(words));
    assert_eq!(read.to_exif_code(), None, "there is no tag to invent");
    assert_eq!(read.rotation(), None, "it is not a quarter turn");
    assert_eq!(read.linear(), odd, "the linear projection still answers");
    assert_eq!(read.matrix(), words, "and nothing was dropped");
    // The determinant still answers, because a reflection is a
    // determinant sign whatever the angle.
    assert!(!read.is_mirrored());
    assert!(ImageOrientation::Other([65536, 0, 0, 0, -65536, 0, 0, 0, 1 << 30]).is_mirrored());
  }

  #[test]
  fn a_noncanonical_word_keeps_a_matrix_out_of_the_named_variants() {
    // The escape-carries-never-collapses law, at the exact place it was
    // being broken: a matrix whose *linear* four say "quarter turn
    // clockwise" but which also translates, or projects, is not tag 6.
    // Reading it as tag 6 throws away the word that made it different.
    //
    // Every non-linear word, one at a time, against a linear part that
    // would otherwise be named.
    let named = ImageOrientation::RightTop;
    let canonical = named.matrix();
    assert_eq!(
      ImageOrientation::from_display_matrix(&words_to_bytes(canonical)),
      Some(named),
      "the canonical matrix must still be named",
    );

    for index in [2usize, 5, 6, 7, 8] {
      let mut forged = canonical;
      // A value that is wrong for that slot: any non-zero for the
      // translation and perspective terms, anything but unity for `w`.
      forged[index] = if index == 8 { 1 << 29 } else { 4_096 };
      let read = ImageOrientation::from_display_matrix(&words_to_bytes(forged))
        .expect("nine words are readable");
      assert_eq!(
        read,
        ImageOrientation::Other(forged),
        "word {index} was collapsed into a named variant",
      );
      assert_eq!(read.to_exif_code(), None, "word {index}");
      assert_eq!(read.matrix(), forged, "word {index} round-trips whole");
      // The four that do carry the orientation are still projectable.
      assert_eq!(read.linear(), named.linear(), "word {index}");
    }
  }

  #[test]
  fn the_escape_round_trips_every_word_losslessly() {
    // Nine distinct, deliberately hostile words: negative, extreme,
    // and nothing canonical anywhere.
    let words: [i32; 9] = [1, -2, 3, -4, 5, -6, i32::MIN, i32::MAX, 0];
    let read = ImageOrientation::from_display_matrix(&words_to_bytes(words)).expect("readable");
    assert_eq!(read, ImageOrientation::Other(words));
    assert_eq!(read.matrix(), words);
    // And back through the bytes again: the escape is a fixed point.
    let again =
      ImageOrientation::from_display_matrix(&words_to_bytes(read.matrix())).expect("readable");
    assert_eq!(again, read);
  }

  #[test]
  fn every_named_orientation_reconstructs_its_canonical_matrix() {
    for (tag, orientation, linear) in MEASURED {
      let matrix = orientation.matrix();
      assert_eq!(
        [matrix[0], matrix[1], matrix[3], matrix[4]],
        linear,
        "tag {tag}",
      );
      assert_eq!(
        [matrix[2], matrix[5], matrix[6], matrix[7]],
        [0, 0, 0, 0],
        "tag {tag}: no translation, no perspective",
      );
      assert_eq!(matrix[8], 1 << 30, "tag {tag}: unity `w`");
      // Round-trip: the reconstruction reads back as the same value.
      assert_eq!(
        ImageOrientation::from_display_matrix(&words_to_bytes(matrix)),
        Some(orientation),
        "tag {tag}",
      );
    }
  }

  #[test]
  fn a_malformed_matrix_is_no_orientation_rather_than_a_guessed_one() {
    assert_eq!(ImageOrientation::from_display_matrix(&[]), None);
    assert_eq!(ImageOrientation::from_display_matrix(&[0u8; 16]), None);
    assert_eq!(ImageOrientation::from_display_matrix(&[0u8; 40]), None);
    // The one length that is right.
    assert_eq!(
      ImageOrientation::DISPLAY_MATRIX_BYTES,
      36,
      "nine int32, per libavutil/display.h",
    );
    assert!(ImageOrientation::from_display_matrix(&[0u8; 36]).is_some());
  }

  #[test]
  fn an_out_of_range_exif_tag_is_refused_not_clamped() {
    for code in [0u16, 9, 255, u16::MAX] {
      assert_eq!(ImageOrientation::from_exif_code(code), None, "code {code}");
    }
  }

  #[test]
  fn the_orientation_seat_rides_the_image_extras() {
    let extra = ImageFrameExtra::default();
    assert_eq!(extra.orientation(), None, "absent until a file says");

    let carried = ImageFrameExtra::new().with_orientation(Some(ImageOrientation::RightTop));
    assert_eq!(carried.orientation(), Some(ImageOrientation::RightTop));

    let mut mutated = carried.clone();
    mutated.set_orientation(None);
    assert_eq!(mutated.orientation(), None);
    assert_eq!(carried.orientation(), Some(ImageOrientation::RightTop));
  }

  #[test]
  fn the_image_household_is_one_seat() {
    let extra = ImageFrameExtra::default();
    assert!(extra.side_data().is_empty());
    let carried = ImageFrameExtra::new().with_side_data(vec![SideDataEntry::new(
      3,
      FfmpegBytes::copy_from_slice(&[1]),
    )]);
    assert_eq!(carried.side_data().len(), 1);
    assert_eq!(carried.side_data()[0].kind(), 3);
    let mut mutated = carried.clone();
    mutated.set_side_data(Vec::new());
    assert!(mutated.side_data().is_empty());
    assert_eq!(carried.side_data().len(), 1);
  }

  #[test]
  fn content_light_level_default_is_zero() {
    let cll = ContentLightLevel::default();
    assert_eq!(cll.max_cll(), 0);
    assert_eq!(cll.max_fall(), 0);
  }

  #[test]
  fn builders_chain() {
    let v = VideoPacketExtra::new(7)
      .with_byte_pos(Some(1234))
      .with_side_data(vec![SideDataEntry::new(
        1,
        FfmpegBytes::copy_from_slice(&[0xAB]),
      )]);
    assert_eq!(v.stream_index(), 7);
    assert_eq!(v.byte_pos(), Some(1234));
    assert_eq!(v.side_data().len(), 1);
  }

  #[test]
  fn setters_chain() {
    let mut v = VideoPacketExtra::default();
    v.set_stream_index(3).set_byte_pos(Some(99));
    assert_eq!(v.stream_index(), 3);
    assert_eq!(v.byte_pos(), Some(99));
  }
}