oxideav-rtmp 0.0.4

Pure-Rust RTMP (ingest + push) for oxideav — server accepts publishers, client pushes to remote servers, with a pluggable key-verification hook
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
//! FLV-tag payload shape for RTMP audio / video messages.
//!
//! Real RTMP always carries H.264 + AAC (plus MP3 / Speex / Nellymoser
//! for audio on legacy flows; we treat those as opaque). The payload
//! layout inside type-8 / type-9 messages matches what an `.flv` file
//! stores in its audio / video tags, so the parsing code is identical
//! to FLV's.
//!
//! Callers of this module work in terms of:
//!
//! * [`VideoTag`] — frame type + codec + AVC packet type + NALU-ish
//!   body. For H.264, the first video message of a stream is an
//!   "AVC sequence header" (= `AVCDecoderConfigurationRecord`, aka
//!   avcC). Every subsequent keyframe / interframe is
//!   `AVCPacketType = 1` with length-prefixed NALUs.
//!
//! * [`AudioTag`] — format + rate/size/channels + AAC packet type +
//!   raw payload. For AAC, the first audio message is the
//!   `AudioSpecificConfig` (2-byte ASC for LC-AAC 44.1k stereo);
//!   subsequent messages carry raw AAC frames.
//!
//! These shapes are stable across every RTMP implementation — OBS,
//! Wirecast, ffmpeg's rtmpproto, node-media-server all emit the same
//! bytes.

use crate::error::{Error, Result};

// §E.4.3 "Video tag body" (FLV 10.1 spec annex E).
// frame type (high nibble of byte 0):
pub const VIDEO_FRAME_KEYFRAME: u8 = 1; // "seekable frame" aka IDR
pub const VIDEO_FRAME_INTER: u8 = 2;
pub const VIDEO_FRAME_DISPOSABLE: u8 = 3; // H.263 only
pub const VIDEO_FRAME_GENERATED_KEY: u8 = 4;
pub const VIDEO_FRAME_INFO: u8 = 5;

// codec id (low nibble of byte 0):
pub const VIDEO_CODEC_H263: u8 = 2;
pub const VIDEO_CODEC_SCREEN: u8 = 3;
pub const VIDEO_CODEC_VP6: u8 = 4;
pub const VIDEO_CODEC_VP6A: u8 = 5;
pub const VIDEO_CODEC_SCREEN_V2: u8 = 6;
pub const VIDEO_CODEC_AVC: u8 = 7; // H.264 — the one anyone uses in 2026

pub const AVC_PACKET_TYPE_SEQUENCE_HEADER: u8 = 0;
pub const AVC_PACKET_TYPE_NALU: u8 = 1;
pub const AVC_PACKET_TYPE_END_OF_SEQUENCE: u8 = 2;

// Enhanced RTMP v1, Table 4 "Extended VideoTagHeader" (Veovera
// Software Organization, 2023-2025). When the high bit of byte 0
// (the IsExHeader flag, value 0x80) is set, the low nibble is a
// `PacketType` rather than a legacy `CodecID`, and the four bytes
// that follow are a FourCC video-codec tag rather than the
// legacy AVC packet-type + composition-time bytes.
//
// IsExHeader sits at bit 7 of the first byte. Pre-2023 FLV
// `FrameType` values never reached 8, so the bit was always zero
// for legacy publishers — Enhanced RTMP repurposes it without
// breaking those clients (per the spec's backwards-compatibility
// note).
pub const VIDEO_IS_EX_HEADER: u8 = 0x80;

// Enhanced RTMP §"Defining Additional Video Codecs", Table 4 row
// `PacketType (i.e. not CodecId) — IF IsExHeader == 1, UB[4]`.
pub const EX_PACKET_TYPE_SEQUENCE_START: u8 = 0;
pub const EX_PACKET_TYPE_CODED_FRAMES: u8 = 1;
pub const EX_PACKET_TYPE_SEQUENCE_END: u8 = 2;
/// `CodedFramesX` — like `CodedFrames` but the SI24
/// `CompositionTime` is implied to be zero and therefore omitted
/// from the wire to save three bytes.
pub const EX_PACKET_TYPE_CODED_FRAMES_X: u8 = 3;
/// `Metadata` — the VideoTagBody carries an AMF-encoded `[name,
/// value]` metadata pair instead of coded video. The only
/// `name` Enhanced RTMP v1 defines is `"colorInfo"` (HDR
/// signalling). When this PacketType is present the `FrameType`
/// flags at the top of the header are required (per spec) to be
/// ignored.
pub const EX_PACKET_TYPE_METADATA: u8 = 4;
/// `MPEG2TSSequenceStart` — sequence-start variant whose body is
/// the codec's MPEG-2-TS-format descriptor (used by AV1's
/// `AV1VideoDescriptor`, mutually exclusive with
/// `PacketTypeSequenceStart` per the 2023-06-07 revision note).
pub const EX_PACKET_TYPE_MPEG2TS_SEQUENCE_START: u8 = 5;
/// `Multitrack` — turns on video multitrack mode. Body shape
/// (AvMultitrackType + per-track FourCc + track id + size) is
/// deferred to a follow-up round.
pub const EX_PACKET_TYPE_MULTITRACK: u8 = 6;
/// `ModEx` — modifier/extension marker that introduces a chain of
/// size-prefixed ModEx packets before the *real* VideoPacketType is
/// read (`enhanced-rtmp-v2.pdf` §"ExVideoTagHeader" — the
/// `while (videoPacketType == VideoPacketType.ModEx)` loop). One of
/// these chains can carry high-precision timestamps
/// (`TimestampOffsetNano`) or other future per-message modifiers.
pub const EX_PACKET_TYPE_MOD_EX: u8 = 7;

/// `enum VideoPacketModExType` / `enum AudioPacketModExType`
/// (`enhanced-rtmp-v2.pdf` §"ExVideoTagHeader" / §"ExAudioTagHeader").
/// `TimestampOffsetNano = 0` is the only subtype defined today: the
/// ModEx data carries a `bytesToUI24` nanosecond offset (0..=999_999
/// ns) added to the current media message's presentation time
/// without altering the core RTMP millisecond timestamp.
pub const MOD_EX_TYPE_TIMESTAMP_OFFSET_NANO: u8 = 0;

/// One entry in the Enhanced RTMP v2 ModEx prelude chain
/// (`enhanced-rtmp-v2.pdf` §"ExVideoTagHeader" / §"ExAudioTagHeader").
///
/// On the wire each entry is `modExDataSize` (1-byte `UI8 + 1`, or a
/// 16-bit `UI16 + 1` escape when the 8-bit form would be 256),
/// followed by `modExDataSize` bytes of `modExData`, then a single
/// byte whose high nibble is the [`mod_ex_type`][ModEx::mod_ex_type]
/// (`UB[4]`) and whose low nibble is the *next* PacketType (`UB[4]`).
/// The decoded struct keeps only the per-entry payload; the trailing
/// nibble byte is reconstructed from the chain order + the tag's real
/// packet type when re-encoding.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ModEx {
    /// `AudioPacketModExType` / `VideoPacketModExType` — the high
    /// nibble of the byte that follows the data. One of
    /// `MOD_EX_TYPE_*` (only `TimestampOffsetNano = 0` defined today).
    pub mod_ex_type: u8,
    /// Raw `modExData` bytes (1..=65536 bytes). For
    /// `TimestampOffsetNano` this is at least 3 bytes whose first
    /// three big-endian bytes are the UI24 nanosecond offset.
    pub data: Vec<u8>,
}

impl ModEx {
    /// Decode the `TimestampOffsetNano` value (`bytesToUI24` of the
    /// first three `data` bytes) when this entry is that subtype.
    /// Returns `None` for any other `mod_ex_type` or if `data` is
    /// shorter than the spec-mandated three bytes.
    pub fn timestamp_offset_nano(&self) -> Option<u32> {
        if self.mod_ex_type != MOD_EX_TYPE_TIMESTAMP_OFFSET_NANO || self.data.len() < 3 {
            return None;
        }
        Some(((self.data[0] as u32) << 16) | ((self.data[1] as u32) << 8) | (self.data[2] as u32))
    }

    /// Build a `TimestampOffsetNano` ModEx entry from a nanosecond
    /// offset (0..=999_999 ns per spec) encoded as a `bytesToUI24`
    /// 3-byte big-endian payload.
    pub fn timestamp_offset_nano_entry(nano: u32) -> ModEx {
        ModEx {
            mod_ex_type: MOD_EX_TYPE_TIMESTAMP_OFFSET_NANO,
            data: vec![(nano >> 16) as u8, (nano >> 8) as u8, nano as u8],
        }
    }
}

/// Parse a ModEx prelude chain starting at `payload[start]` (the
/// `payload[start - 1]` low nibble was already decoded as
/// `PacketType.ModEx`). Returns the decoded entries, the *real*
/// PacketType nibble that terminates the chain, and the offset of
/// the first byte after the chain.
///
/// Per `enhanced-rtmp-v2.pdf` the loop is identical for audio and
/// video: read `modExDataSize` (`UI8 + 1`, escaping to `UI16 + 1`
/// when the 8-bit form would be 256), read that many data bytes,
/// then read one nibble byte (`modExType:UB[4] | packetType:UB[4]`)
/// — repeating while the new packetType is again `ModEx`.
fn parse_mod_ex_chain(
    payload: &[u8],
    start: usize,
    mod_ex_value: u8,
    what: &str,
) -> Result<(Vec<ModEx>, u8, usize)> {
    let mut pos = start;
    let mut chain = Vec::new();
    loop {
        // modExDataSize = UI8 + 1
        if pos >= payload.len() {
            return Err(Error::Other(format!(
                "Enhanced RTMP {what} ModEx: truncated reading modExDataSize"
            )));
        }
        let mut size = payload[pos] as usize + 1;
        pos += 1;
        // If the 8-bit form maxes out (== 256), a UI16 + 1 follows.
        if size == 256 {
            if pos + 2 > payload.len() {
                return Err(Error::Other(format!(
                    "Enhanced RTMP {what} ModEx: truncated reading 16-bit modExDataSize"
                )));
            }
            size = (((payload[pos] as usize) << 8) | (payload[pos + 1] as usize)) + 1;
            pos += 2;
        }
        // modExData = UI8[modExDataSize]
        if pos + size > payload.len() {
            return Err(Error::Other(format!(
                "Enhanced RTMP {what} ModEx: truncated reading {size}-byte modExData"
            )));
        }
        let data = payload[pos..pos + size].to_vec();
        pos += size;
        // nibble byte: modExType (UB[4], high) | packetType (UB[4], low)
        if pos >= payload.len() {
            return Err(Error::Other(format!(
                "Enhanced RTMP {what} ModEx: truncated reading modExType/packetType nibble"
            )));
        }
        let nibble = payload[pos];
        pos += 1;
        let mod_ex_type = (nibble >> 4) & 0x0F;
        let next_packet_type = nibble & 0x0F;
        chain.push(ModEx { mod_ex_type, data });
        if next_packet_type != mod_ex_value {
            return Ok((chain, next_packet_type, pos));
        }
        // Another ModEx entry follows.
    }
}

/// Append a ModEx prelude chain to `out`. Each entry writes the
/// `modExDataSize` (`UI8 + 1`, or the `0xFF` + `UI16 + 1` escape
/// when the data is 257..=65536 bytes), the data bytes, and a nibble
/// byte whose high nibble is the entry's `mod_ex_type` and whose low
/// nibble is the PacketType to read *next* — `ModEx` for every entry
/// except the last, whose low nibble is the real `packet_type`.
fn build_mod_ex_chain(out: &mut Vec<u8>, chain: &[ModEx], mod_ex_value: u8, real_packet_type: u8) {
    for (i, entry) in chain.iter().enumerate() {
        let len = entry.data.len();
        // UI8 form covers 1..=255 bytes (stored as len - 1, 0..=254).
        // A stored UI8 of 255 means modExDataSize == 256, which the
        // parser reads as the "switch to UI16" escape — so 256..=65536
        // bytes always take the escape form (UI16 = len - 1).
        if (1..=255).contains(&len) {
            out.push((len - 1) as u8);
        } else {
            // UI16 escape: emit 0xFF (the 8-bit 256 sentinel), then
            // (len - 1) as UI16. len is clamped to the 16-bit range.
            out.push(0xFF);
            let v16 = (len.saturating_sub(1)).min(0xFFFF) as u16;
            out.push((v16 >> 8) as u8);
            out.push(v16 as u8);
        }
        out.extend_from_slice(&entry.data);
        // The terminating nibble byte points at the *next* packet
        // type: ModEx while more entries follow, the real type last.
        let next = if i + 1 < chain.len() {
            mod_ex_value
        } else {
            real_packet_type
        };
        out.push(((entry.mod_ex_type & 0x0F) << 4) | (next & 0x0F));
    }
}

// Enhanced RTMP §"Defining Additional Video Codecs", Table 4
// "Video FourCC" row. FourCCs are read as four ASCII bytes in
// reading order (i.e. `'a','v','0','1'`), interpreted as a UI32
// big-endian for comparison (`0x6176_3031`).
//
// `av01` / `vp09` / `hvc1` were added in Enhanced RTMP v1
// (Veovera 2023). `vp08` (VP8), `avc1` (FourCC-mode AVC/H.264),
// and `vvc1` (VVC/H.266) were added in Enhanced RTMP v2
// (Veovera 2026) — see enhanced-rtmp-v2.pdf §"Enhanced Video"
// `enum VideoFourCc { Vp8, Vp9, Av1, Avc, Hevc, Vvc }`.
pub const FOURCC_AV1: [u8; 4] = *b"av01";
pub const FOURCC_VP9: [u8; 4] = *b"vp09";
pub const FOURCC_HEVC: [u8; 4] = *b"hvc1";
/// Enhanced RTMP v2 — VP8 FourCC. SequenceStart body is a
/// `VPCodecConfigurationRecord` (same shape as VP9). CodedFrames
/// body is one or more full VP8 frames. CTS not on the wire (no
/// B-frames).
pub const FOURCC_VP8: [u8; 4] = *b"vp08";
/// Enhanced RTMP v2 — AVC/H.264 in FourCC mode. SequenceStart body
/// is the `AVCDecoderConfigurationRecord`; CodedFrames body is
/// one or more length-prefixed NALUs. Per
/// enhanced-rtmp-v2.pdf §"ExVideoTagBody" the SI24
/// `compositionTimeOffset` is on the wire for AVC + CodedFrames
/// (parallel to HEVC's row), and implied zero for
/// CodedFramesX.
pub const FOURCC_AVC: [u8; 4] = *b"avc1";
/// Enhanced RTMP v2 — VVC/H.266 FourCC. SequenceStart body is the
/// `VVCDecoderConfigurationRecord` (per ISO/IEC 14496-15:2024
/// §11.2.4.2). CodedFrames body is one or more length-prefixed
/// NALUs. Per §"ExVideoTagBody" the SI24
/// `compositionTimeOffset` is on the wire for VVC + CodedFrames
/// (mirrors AVC + HEVC) and implied zero for CodedFramesX.
pub const FOURCC_VVC: [u8; 4] = *b"vvc1";

// §E.4.2 "Audio tag body".
// sound format (high nibble of byte 0):
pub const AUDIO_FORMAT_PCM_LE: u8 = 0;
pub const AUDIO_FORMAT_ADPCM: u8 = 1;
pub const AUDIO_FORMAT_MP3: u8 = 2;
pub const AUDIO_FORMAT_PCM_LE_8BIT: u8 = 3;
pub const AUDIO_FORMAT_NELLYMOSER_16K_MONO: u8 = 4;
pub const AUDIO_FORMAT_NELLYMOSER_8K_MONO: u8 = 5;
pub const AUDIO_FORMAT_NELLYMOSER: u8 = 6;
pub const AUDIO_FORMAT_G711_ALAW: u8 = 7;
pub const AUDIO_FORMAT_G711_MULAW: u8 = 8;
pub const AUDIO_FORMAT_AAC: u8 = 10;
pub const AUDIO_FORMAT_SPEEX: u8 = 11;

// Enhanced RTMP v2, "Extended AudioTagHeader" (Veovera Software
// Organization, 2026-01-31). When the high nibble of the FLV
// AudioTagHeader byte (SoundFormat) equals `ExHeader = 9`, the
// low UB[4] is reinterpreted as an `AudioPacketType` rather than
// the legacy SoundRate(UB[2]) | SoundSize(UB[1]) | SoundType(UB[1])
// bit field, and the four bytes that follow are an `AudioFourCc`
// rather than the AAC packet-type marker.
//
// Spec: enhanced-rtmp-v2.pdf §"Enhanced Audio", `Extended
// AudioTagHeader` table (`soundFormat = UB[4] as SoundFormat`,
// `if soundFormat == SoundFormat.ExHeader { audioPacketType =
// UB[4] as AudioPacketType }`). Legacy publishers leave the
// high nibble in `0..=8 / 10..=11 / 14..=15` and the parser /
// builder retain the pre-2023 single-byte format unchanged.
pub const AUDIO_FORMAT_EX_HEADER: u8 = 9;

// AudioPacketType enum from the same Extended AudioTagHeader
// table. The values that carry semantics today:
pub const AUDIO_PACKET_TYPE_SEQUENCE_START: u8 = 0;
pub const AUDIO_PACKET_TYPE_CODED_FRAMES: u8 = 1;
/// `SequenceEnd` — signals end of the audio sequence for the
/// current track. Spec: "AudioPacketType.SequenceEnd is to have no
/// less than the same meaning as a silence message".
pub const AUDIO_PACKET_TYPE_SEQUENCE_END: u8 = 2;
/// `MultichannelConfig` — body specifies AudioChannelOrder +
/// channel count + (optionally) per-channel speaker mapping or a
/// 32-bit AudioChannelFlags mask. See §"ExAudioTagBody" pseudocode
/// for the layout.
pub const AUDIO_PACKET_TYPE_MULTICHANNEL_CONFIG: u8 = 4;
/// `Multitrack` — turns on audio multitrack mode. Body shape
/// (AvMultitrackType + per-track FourCc + track id +
/// sizeOfAudioTrack) is deferred to a follow-up round.
pub const AUDIO_PACKET_TYPE_MULTITRACK: u8 = 5;
/// `ModEx` — modifier/extension marker that introduces a chain
/// of size-prefixed ModEx packets before the real AudioPacketType
/// is read. The only ModEx subtype defined today is
/// `TimestampOffsetNano = 0`. Deferred to a follow-up round.
pub const AUDIO_PACKET_TYPE_MOD_EX: u8 = 7;

// Enhanced RTMP v2 §"Enhanced Audio", `enum AudioFourCc` block.
// FourCCs are read as four ASCII bytes in reading order
// (e.g. `'O','p','u','s'`), interpreted as a big-endian UI32 for
// comparison.
pub const FOURCC_AC3: [u8; 4] = *b"ac-3";
pub const FOURCC_EAC3: [u8; 4] = *b"ec-3";
pub const FOURCC_OPUS: [u8; 4] = *b"Opus";
pub const FOURCC_MP3: [u8; 4] = *b".mp3";
pub const FOURCC_FLAC: [u8; 4] = *b"fLaC";
pub const FOURCC_AAC: [u8; 4] = *b"mp4a";

pub const AAC_PACKET_TYPE_SEQUENCE_HEADER: u8 = 0;
pub const AAC_PACKET_TYPE_RAW: u8 = 1;

/// Decoded FLV video-tag header + payload. For H.264 the
/// `composition_time` is the signed CTS offset (ms) between the
/// decoder timestamp the RTMP chunk carries and the presentation
/// timestamp — callers add this to the chunk ts to get PTS.
///
/// **Legacy-vs-Enhanced-RTMP discriminator.** `fourcc` is the
/// signal: `None` = legacy single-byte `codec_id` framing
/// (`avcC` / H.263 / VP6 / FlashSV); `Some([..])` = Enhanced RTMP
/// (Veovera 2023) where `codec_id` is reserved-zero on the wire,
/// `ex_packet_type` is the `PacketType` low nibble, and `body`
/// follows the per-FourCC shape laid out in
/// `enhanced-rtmp-v1.pdf` §"Defining Additional Video Codecs"
/// (HEVCDecoderConfigurationRecord / `AV1CodecConfigurationRecord`
/// / `VPCodecConfigurationRecord` for `SequenceStart`, NALUs / OBUs /
/// frames for `CodedFrames(X)`, AMF metadata for `Metadata`).
///
/// `composition_time` carries the SI24 CTS in both modes — it is
/// only emitted on the wire for legacy AVC (`codec_id == 7`),
/// and for the three NALU-based Enhanced-RTMP FourCCs paired
/// with PacketType = `CodedFrames`: `hvc1` (HEVC, v1), `avc1`
/// (AVC, v2), `vvc1` (VVC, v2). For `CodedFramesX` and the
/// non-NALU FourCCs (`av01`, `vp09`, `vp08`) the field is zero
/// and not encoded on the wire.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VideoTag {
    pub frame_type: u8,
    pub codec_id: u8,
    /// `AvcSequenceHeader` / `AvcNalu` / `AvcEndOfSequence`. `None`
    /// for non-AVC codecs where the first AVC-specific byte doesn't
    /// exist. Stays `None` for Enhanced RTMP tags too — use
    /// [`VideoTag::ex_packet_type`] instead.
    pub avc_packet_type: Option<u8>,
    pub composition_time: i32,
    /// Body: `AVCDecoderConfigurationRecord` for AVC sequence
    /// headers; a sequence of `[u32 length-BE][NALU bytes]` pairs
    /// for AVC / HEVC NALU packets; AV1 OBUs for `av01`; full VP9
    /// frames for `vp09`; AMF-encoded `[name, value]` pairs for
    /// Enhanced RTMP `PacketTypeMetadata`.
    pub body: Vec<u8>,
    /// Enhanced RTMP v1 `PacketType` nibble (the four bits that
    /// replace `CodecID` when the `IsExHeader` flag is set). One
    /// of `EX_PACKET_TYPE_*`. `None` for legacy tags.
    pub ex_packet_type: Option<u8>,
    /// Enhanced RTMP FourCC video codec tag — the four ASCII
    /// bytes following the header byte when `IsExHeader == 1`.
    /// `None` for legacy tags. Values defined by Veovera so far:
    /// `b"av01"` (AV1, v1), `b"vp09"` (VP9, v1), `b"hvc1"`
    /// (HEVC, v1), `b"vp08"` (VP8, v2), `b"avc1"` (AVC/H.264 in
    /// FourCC mode, v2), `b"vvc1"` (VVC/H.266, v2).
    pub fourcc: Option<[u8; 4]>,
    /// Enhanced RTMP v2 ModEx prelude chain
    /// (`enhanced-rtmp-v2.pdf` §"ExVideoTagHeader"). Empty for
    /// legacy tags and for Enhanced tags that carry no modifier.
    /// Each entry was a `PacketType.ModEx` step before the real
    /// [`ex_packet_type`][VideoTag::ex_packet_type] was decoded;
    /// the chain is re-emitted verbatim ahead of the real packet
    /// type on build. The only subtype defined today is
    /// `TimestampOffsetNano` (high-precision sub-millisecond
    /// presentation offset).
    pub mod_ex: Vec<ModEx>,
}

impl VideoTag {
    pub fn is_keyframe(&self) -> bool {
        self.frame_type == VIDEO_FRAME_KEYFRAME || self.frame_type == VIDEO_FRAME_GENERATED_KEY
    }
    pub fn is_avc_sequence_header(&self) -> bool {
        self.codec_id == VIDEO_CODEC_AVC
            && self.avc_packet_type == Some(AVC_PACKET_TYPE_SEQUENCE_HEADER)
    }
    /// True when this tag is the FourCC-mode `PacketTypeSequenceStart`
    /// for an Enhanced-RTMP codec (`body` is the codec's
    /// configuration record — `HEVCDecoderConfigurationRecord` for
    /// `hvc1`, `AV1CodecConfigurationRecord` for `av01`,
    /// `VPCodecConfigurationRecord` for `vp09` / `vp08`,
    /// `AVCDecoderConfigurationRecord` for `avc1`,
    /// `VVCDecoderConfigurationRecord` for `vvc1`).
    pub fn is_ex_sequence_header(&self) -> bool {
        self.fourcc.is_some() && self.ex_packet_type == Some(EX_PACKET_TYPE_SEQUENCE_START)
    }
    /// True when this tag carries an Enhanced-RTMP
    /// `PacketTypeMetadata` body (HDR `colorInfo` and the like).
    /// Per Enhanced RTMP v1 the `FrameType` flags above the
    /// PacketType nibble are required to be ignored when this is
    /// set, so callers that classify keyframe vs interframe must
    /// short-circuit on this predicate first.
    pub fn is_ex_metadata(&self) -> bool {
        self.fourcc.is_some() && self.ex_packet_type == Some(EX_PACKET_TYPE_METADATA)
    }

    /// Sum of the `TimestampOffsetNano` ModEx entries on this tag, in
    /// nanoseconds. Per `enhanced-rtmp-v2.pdf` the offset is added to
    /// the current media message's presentation time without altering
    /// the core RTMP millisecond timestamp. Returns `0` when no such
    /// entry is present.
    pub fn timestamp_offset_nano(&self) -> u32 {
        self.mod_ex
            .iter()
            .filter_map(ModEx::timestamp_offset_nano)
            .fold(0u32, |acc, n| acc.saturating_add(n))
    }
}

// 24-bit signed → i32 sign-extend. The wire format ("FLV
// Composition Time", FLV §E.4.3.1, also Enhanced RTMP HEVC
// CodedFrames row) packs SI24 in three big-endian bytes.
fn sign_extend_si24(raw: i32) -> i32 {
    if raw & 0x0080_0000 != 0 {
        raw | -0x0100_0000i32
    } else {
        raw
    }
}

/// Decode the FLV video-tag header from an RTMP video message payload.
///
/// Recognises both pre-2023 legacy framing (1-byte
/// `frame_type|codec_id` header, optional AVC packet-type +
/// SI24 CTS) and Enhanced RTMP v1 framing (`IsExHeader` flag in
/// bit 7 → 1-byte `is_ex|frame_type|packet_type` header, 4-byte
/// FourCC, optional SI24 CTS for HEVC `CodedFrames`).
///
/// Returns `Err(Error::Other)` on truncation. Per Enhanced RTMP
/// v1 the spec says: "During parsing, logic must gracefully
/// fail if at any point important signaling/flags (ex.
/// FrameType, IsExHeader, ExHeaderInfo) are not understood." —
/// we surface an unknown `ex_packet_type` by returning the raw
/// nibble in the struct (callers decide whether to ignore the
/// tag or fail).
pub fn parse_video(payload: &[u8]) -> Result<VideoTag> {
    if payload.is_empty() {
        return Err(Error::Other("FLV video tag: empty".into()));
    }
    let b0 = payload[0];
    if (b0 & VIDEO_IS_EX_HEADER) != 0 {
        // --- Enhanced RTMP v1/v2 framing ---
        //
        //   byte 0      = IsExHeader(1) | FrameType(3) | PacketType(4)
        //   [ModEx prelude chain — present only when PacketType == ModEx]
        //   byte ..=+3  = FourCC (4 ASCII bytes)
        //   byte ..     = body, with shape depending on FourCC × PacketType
        //
        // Per spec, when PacketType == Metadata the FrameType
        // flags above the nibble are required to be ignored;
        // we still preserve the raw bits in `frame_type` so
        // callers that diff fixtures can see them.
        let frame_type = (b0 >> 4) & 0b0111;
        let mut packet_type = b0 & 0x0F;
        let mut pos = 1;

        // ModEx prelude (enhanced-rtmp-v2.pdf §"ExVideoTagHeader"):
        // while the freshly-read PacketType nibble is ModEx, consume
        // a size-prefixed modExData entry + the trailing
        // modExType/packetType nibble byte, looping until a non-ModEx
        // PacketType terminates the chain. The chain sits between the
        // header byte and the FourCC.
        let mut mod_ex = Vec::new();
        if packet_type == EX_PACKET_TYPE_MOD_EX {
            let (chain, real_pt, next) =
                parse_mod_ex_chain(payload, pos, EX_PACKET_TYPE_MOD_EX, "video")?;
            mod_ex = chain;
            packet_type = real_pt;
            pos = next;
        }

        if pos + 4 > payload.len() {
            return Err(Error::Other(
                "Enhanced RTMP video tag: need 4 bytes for FourCC after header/ModEx".into(),
            ));
        }
        let mut fcc = [0u8; 4];
        fcc.copy_from_slice(&payload[pos..pos + 4]);
        pos += 4;

        // SI24 CompositionTime is on the wire only for the
        // three NALU-based FourCCs paired with
        // PacketTypeCodedFrames (Enhanced RTMP v1 added HEVC;
        // Enhanced RTMP v2 §"ExVideoTagBody" adds AVC and VVC
        // with the same `compositionTimeOffset = SI24` row in
        // the pseudocode). For CodedFramesX the spec says:
        // "compositionTimeOffset is implied to equal zero. This
        // is an optimization to save putting SI24 value on the
        // wire." All other FourCCs (av01, vp09, vp08) and all
        // other PacketTypes have no CTS field — the body
        // follows the FourCC directly.
        let needs_cts = packet_type == EX_PACKET_TYPE_CODED_FRAMES
            && (fcc == FOURCC_HEVC || fcc == FOURCC_AVC || fcc == FOURCC_VVC);
        let (cts, body_start) = if needs_cts {
            if pos + 3 > payload.len() {
                return Err(Error::Other(
                    "Enhanced RTMP / HEVC CodedFrames: need 3 bytes for SI24 CTS".into(),
                ));
            }
            let raw = ((payload[pos] as i32) << 16)
                | ((payload[pos + 1] as i32) << 8)
                | (payload[pos + 2] as i32);
            (sign_extend_si24(raw), pos + 3)
        } else {
            (0, pos)
        };

        Ok(VideoTag {
            frame_type,
            codec_id: 0, // reserved in extended mode; legacy nibble unused.
            avc_packet_type: None,
            composition_time: cts,
            body: payload[body_start..].to_vec(),
            ex_packet_type: Some(packet_type),
            fourcc: Some(fcc),
            mod_ex,
        })
    } else {
        // --- Legacy pre-2023 framing ---
        let frame_type = b0 >> 4;
        let codec_id = b0 & 0x0F;
        if codec_id == VIDEO_CODEC_AVC {
            if payload.len() < 5 {
                return Err(Error::Other("FLV/AVC tag: need 5+ bytes".into()));
            }
            let apt = payload[1];
            let cts_raw =
                ((payload[2] as i32) << 16) | ((payload[3] as i32) << 8) | (payload[4] as i32);
            Ok(VideoTag {
                frame_type,
                codec_id,
                avc_packet_type: Some(apt),
                composition_time: sign_extend_si24(cts_raw),
                body: payload[5..].to_vec(),
                ex_packet_type: None,
                fourcc: None,
                mod_ex: Vec::new(),
            })
        } else {
            Ok(VideoTag {
                frame_type,
                codec_id,
                avc_packet_type: None,
                composition_time: 0,
                body: payload[1..].to_vec(),
                ex_packet_type: None,
                fourcc: None,
                mod_ex: Vec::new(),
            })
        }
    }
}

/// Build an RTMP video-tag payload.
///
/// Legacy mode (`tag.fourcc.is_none()`): writes the 1-byte
/// frame/codec header + optional AVC packet type + 3-byte
/// composition time, then `body`.
///
/// Enhanced RTMP mode (`tag.fourcc = Some([..])`): writes the
/// `IsExHeader | frame_type | packet_type` byte, the 4-byte
/// FourCC, the SI24 CTS *only* when FourCC == HEVC and
/// PacketType == CodedFrames (matching Enhanced RTMP v1's
/// "CompositionTime Offset is implied to equal zero" exception
/// for `CodedFramesX` and the non-HEVC FourCCs), then `body`.
pub fn build_video(tag: &VideoTag) -> Vec<u8> {
    if let Some(fcc) = tag.fourcc {
        let packet_type = tag.ex_packet_type.unwrap_or(EX_PACKET_TYPE_CODED_FRAMES);
        // When a ModEx prelude is present the header byte's
        // PacketType nibble is `ModEx`; the *real* packet type is
        // carried by the terminating nibble of the chain
        // (enhanced-rtmp-v2.pdf §"ExVideoTagHeader"). Otherwise the
        // header nibble is the real packet type directly.
        let header_pt = if tag.mod_ex.is_empty() {
            packet_type
        } else {
            EX_PACKET_TYPE_MOD_EX
        };
        // Per Enhanced RTMP §"Defining Additional Video Codecs"
        // FrameType is UB[3] (i.e. lives in bits 4..=6 — bit 7
        // is IsExHeader). Mask to 3 bits before packing.
        let head = VIDEO_IS_EX_HEADER | ((tag.frame_type & 0x07) << 4) | (header_pt & 0x0F);
        let mut out = Vec::with_capacity(tag.body.len() + 8);
        out.push(head);
        build_mod_ex_chain(&mut out, &tag.mod_ex, EX_PACKET_TYPE_MOD_EX, packet_type);
        out.extend_from_slice(&fcc);
        // Mirrors the parse-side `needs_cts` rule: HEVC / AVC /
        // VVC + CodedFrames emit the SI24 composition-time;
        // everything else (CodedFramesX, SequenceStart,
        // SequenceEnd, Metadata, and the non-NALU FourCCs)
        // omits it per Enhanced RTMP v1/v2 §"ExVideoTagBody".
        let cts_on_wire = packet_type == EX_PACKET_TYPE_CODED_FRAMES
            && (fcc == FOURCC_HEVC || fcc == FOURCC_AVC || fcc == FOURCC_VVC);
        if cts_on_wire {
            let cts = tag.composition_time & 0x00FF_FFFF;
            out.extend_from_slice(&[(cts >> 16) as u8, (cts >> 8) as u8, cts as u8]);
        }
        out.extend_from_slice(&tag.body);
        out
    } else {
        let head = (tag.frame_type << 4) | (tag.codec_id & 0x0F);
        let mut out = Vec::with_capacity(tag.body.len() + 5);
        out.push(head);
        if tag.codec_id == VIDEO_CODEC_AVC {
            out.push(tag.avc_packet_type.unwrap_or(AVC_PACKET_TYPE_NALU));
            let cts = tag.composition_time & 0x00FF_FFFF;
            out.extend_from_slice(&[(cts >> 16) as u8, (cts >> 8) as u8, cts as u8]);
        }
        out.extend_from_slice(&tag.body);
        out
    }
}

/// Decoded FLV audio-tag header + payload.
///
/// **Legacy-vs-Enhanced-RTMP discriminator.** `audio_fourcc` is
/// the signal: `None` = legacy pre-2023 single-byte framing
/// (`SoundFormat | SoundRate | SoundSize | SoundType`, optional
/// AAC packet-type marker); `Some([..])` = Enhanced RTMP v2
/// (Veovera 2026) where `sound_format` is reserved-9 (`ExHeader`)
/// on the wire, `ex_packet_type` is the `AudioPacketType` low
/// nibble, `audio_fourcc` is the four ASCII bytes that follow,
/// and `body` is the per-FourCC × per-PacketType payload defined
/// in `enhanced-rtmp-v2.pdf` §"Enhanced Audio" (the
/// `ExAudioTagBody` table).
///
/// The legacy bit-field fields `sound_rate`, `sound_size_16bit`
/// and `stereo` are not interpreted in Enhanced mode — the spec
/// says: "if (soundFormat == SoundFormat.ExHeader) we switch into
/// FOURCC audio mode as defined below. This means that soundRate,
/// soundSize and soundType bits are not interpreted, instead the
/// UB[4] bits are interpreted as an AudioPacketType". We zero
/// them on parse for tags that arrive in Enhanced mode so callers
/// don't accidentally read them as audio configuration.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AudioTag {
    pub sound_format: u8,
    /// 0 = 5.5k / 1 = 11k / 2 = 22k / 3 = 44k. Encoded in the FLV
    /// header but overridden for AAC (always 3 by spec). Ignored
    /// and forced to zero in Enhanced mode (`audio_fourcc.is_some()`).
    pub sound_rate: u8,
    pub sound_size_16bit: bool,
    pub stereo: bool,
    /// `AacSequenceHeader` / `AacRaw`. `None` for non-AAC codecs
    /// and for all Enhanced-mode tags (use [`AudioTag::ex_packet_type`]
    /// instead).
    pub aac_packet_type: Option<u8>,
    /// Enhanced RTMP v2 `AudioPacketType` nibble (the four bits
    /// that replace SoundRate|SoundSize|SoundType when
    /// `sound_format == AUDIO_FORMAT_EX_HEADER`). One of
    /// `AUDIO_PACKET_TYPE_*`. `None` for legacy tags.
    pub ex_packet_type: Option<u8>,
    /// Enhanced RTMP v2 FourCC audio codec tag — the four ASCII
    /// bytes following the header byte when `sound_format ==
    /// AUDIO_FORMAT_EX_HEADER`. `None` for legacy tags. Values
    /// defined by Veovera so far: `b"Opus"`, `b"fLaC"`, `b"ac-3"`,
    /// `b"ec-3"`, `b".mp3"`, `b"mp4a"` (AAC, added FOURCC
    /// signalling).
    pub audio_fourcc: Option<[u8; 4]>,
    /// Body: per-FourCC `…SequenceHeader` for
    /// `PacketTypeSequenceStart` (`OpusSequenceHeader` /
    /// `FlacSequenceHeader` / `AacSequenceHeader`); per-FourCC
    /// `…CodedData` for `PacketTypeCodedFrames` (`Ac3CodedData`,
    /// `OpusCodedData`, `Mp3CodedData`, `AacCodedData`,
    /// `FlacCodedData`); empty for `SequenceEnd`.
    pub body: Vec<u8>,
    /// Enhanced RTMP v2 ModEx prelude chain
    /// (`enhanced-rtmp-v2.pdf` §"ExAudioTagHeader"). Empty for
    /// legacy tags and for Enhanced tags that carry no modifier.
    /// Each entry was an `AudioPacketType.ModEx` step before the
    /// real [`ex_packet_type`][AudioTag::ex_packet_type] was
    /// decoded; the chain is re-emitted verbatim ahead of the real
    /// packet type on build. The only subtype defined today is
    /// `TimestampOffsetNano`.
    pub mod_ex: Vec<ModEx>,
}

impl AudioTag {
    /// True when this tag is an Enhanced-RTMP v2 tag (the
    /// SoundFormat nibble was `ExHeader = 9` on the wire and the
    /// four-byte FourCC + AudioPacketType were decoded into
    /// [`audio_fourcc`][AudioTag::audio_fourcc] /
    /// [`ex_packet_type`][AudioTag::ex_packet_type]).
    pub fn is_enhanced(&self) -> bool {
        self.audio_fourcc.is_some()
    }
    /// True when this tag is a legacy AAC sequence-header
    /// (`AudioSpecificConfig` payload) — `sound_format = 10`,
    /// `aac_packet_type = 0`.
    pub fn is_aac_sequence_header(&self) -> bool {
        self.sound_format == AUDIO_FORMAT_AAC
            && self.aac_packet_type == Some(AAC_PACKET_TYPE_SEQUENCE_HEADER)
    }
    /// True when this tag is the Enhanced-RTMP v2
    /// `PacketTypeSequenceStart` for a FourCC audio codec — body
    /// is the codec's sequence header per `ExAudioTagBody`
    /// (`OpusSequenceHeader` / `FlacSequenceHeader` /
    /// `AacSequenceHeader` ASC; AC-3 / E-AC-3 / MP3 have no
    /// SequenceStart shape defined in v2).
    pub fn is_ex_sequence_header(&self) -> bool {
        self.audio_fourcc.is_some() && self.ex_packet_type == Some(AUDIO_PACKET_TYPE_SEQUENCE_START)
    }

    /// Sum of the `TimestampOffsetNano` ModEx entries on this tag, in
    /// nanoseconds (added to the message presentation time without
    /// altering the RTMP millisecond timestamp). `0` when absent.
    pub fn timestamp_offset_nano(&self) -> u32 {
        self.mod_ex
            .iter()
            .filter_map(ModEx::timestamp_offset_nano)
            .fold(0u32, |acc, n| acc.saturating_add(n))
    }
}

/// Decode the FLV audio-tag header from an RTMP audio message
/// payload.
///
/// Recognises both legacy pre-2023 framing (1-byte
/// `SoundFormat|SoundRate|SoundSize|SoundType` header, optional
/// AAC packet-type marker) and Enhanced RTMP v2 framing
/// (`SoundFormat == ExHeader = 9` → 1-byte
/// `ExHeader|AudioPacketType` header, 4-byte FourCC, per-FourCC
/// body).
///
/// Returns `Err(Error::Other)` on truncation. Per Enhanced RTMP
/// v2: "During the parsing process, the logic MUST handle
/// unexpected or unknown elements gracefully. Specifically, if
/// any critical signaling or flags (e.g., AudioPacketType and
/// AudioFourCc) are not recognized, the system MUST fail in a
/// controlled and predictable manner." We surface an unknown
/// `ex_packet_type` / FourCC by returning the raw bytes in the
/// struct (callers decide whether to ignore the tag or fail).
///
/// The `ModEx` AudioPacketType prelude (a chain of
/// `modExDataSize + modExData + modExType/packetType` entries before
/// the real packet type) is now decoded into [`AudioTag::mod_ex`].
/// The `Multitrack` and `MultichannelConfig` AudioPacketTypes still
/// have nested layouts (per-track FourCC + size-prefixed track chunks;
/// AudioChannelOrder + channel map) deferred to a follow-up round; if
/// the nibble decodes to either value, the body is preserved verbatim
/// and the caller is expected to skip the message rather than
/// interpret it as a normal coded-frame tag.
pub fn parse_audio(payload: &[u8]) -> Result<AudioTag> {
    if payload.is_empty() {
        return Err(Error::Other("FLV audio tag: empty".into()));
    }
    let b0 = payload[0];
    let sound_format = b0 >> 4;
    if sound_format == AUDIO_FORMAT_EX_HEADER {
        // --- Enhanced RTMP v2 framing ---
        //
        //   byte 0     = SoundFormat=9(4) | AudioPacketType(4)
        //   [ModEx prelude chain — present only when packetType == ModEx]
        //   byte ..=+3 = AudioFourCc (4 ASCII bytes)
        //   byte ..    = body, per (FourCc, PacketType) per
        //                §"ExAudioTagBody"
        //
        // Per spec the legacy bit-field SoundRate/SoundSize/
        // SoundType are NOT interpreted in this mode — zero them
        // on the parsed struct so a downstream consumer that
        // (incorrectly) keys off them gets a clearly-zero answer
        // instead of an arbitrary alias of the AudioPacketType
        // nibble.
        let mut packet_type = b0 & 0x0F;
        let mut pos = 1;

        // ModEx prelude (enhanced-rtmp-v2.pdf §"ExAudioTagHeader"):
        // identical loop to the video path — consume size-prefixed
        // modExData + the trailing modExType/packetType nibble while
        // the PacketType nibble is ModEx. The chain sits between the
        // header byte and the FourCC.
        let mut mod_ex = Vec::new();
        if packet_type == AUDIO_PACKET_TYPE_MOD_EX {
            let (chain, real_pt, next) =
                parse_mod_ex_chain(payload, pos, AUDIO_PACKET_TYPE_MOD_EX, "audio")?;
            mod_ex = chain;
            packet_type = real_pt;
            pos = next;
        }

        if pos + 4 > payload.len() {
            return Err(Error::Other(
                "Enhanced RTMP audio tag: need 4 bytes for FourCC after header/ModEx".into(),
            ));
        }
        let mut fcc = [0u8; 4];
        fcc.copy_from_slice(&payload[pos..pos + 4]);
        pos += 4;
        Ok(AudioTag {
            sound_format,
            sound_rate: 0,
            sound_size_16bit: false,
            stereo: false,
            aac_packet_type: None,
            ex_packet_type: Some(packet_type),
            audio_fourcc: Some(fcc),
            body: payload[pos..].to_vec(),
            mod_ex,
        })
    } else {
        // --- Legacy pre-2023 framing ---
        let sound_rate = (b0 >> 2) & 0x03;
        let sound_size_16bit = (b0 & 0x02) != 0;
        let stereo = (b0 & 0x01) != 0;
        if sound_format == AUDIO_FORMAT_AAC {
            if payload.len() < 2 {
                return Err(Error::Other("FLV/AAC tag: need 2+ bytes".into()));
            }
            Ok(AudioTag {
                sound_format,
                sound_rate,
                sound_size_16bit,
                stereo,
                aac_packet_type: Some(payload[1]),
                ex_packet_type: None,
                audio_fourcc: None,
                body: payload[2..].to_vec(),
                mod_ex: Vec::new(),
            })
        } else {
            Ok(AudioTag {
                sound_format,
                sound_rate,
                sound_size_16bit,
                stereo,
                aac_packet_type: None,
                ex_packet_type: None,
                audio_fourcc: None,
                body: payload[1..].to_vec(),
                mod_ex: Vec::new(),
            })
        }
    }
}

/// Build an RTMP audio-tag payload.
///
/// Legacy mode (`tag.audio_fourcc.is_none()`): writes the 1-byte
/// `SoundFormat|SoundRate|SoundSize|SoundType` header + optional
/// 1-byte AAC packet type, then `body`.
///
/// Enhanced RTMP v2 mode (`tag.audio_fourcc = Some([..])`):
/// writes a 1-byte `ExHeader(9) | AudioPacketType` header
/// (regardless of the value sitting in `tag.sound_format` — the
/// spec mandates SoundFormat == 9 for this layout), the 4-byte
/// FourCC, then `body`. The legacy SoundRate / SoundSize /
/// SoundType bits are dropped per spec.
pub fn build_audio(tag: &AudioTag) -> Vec<u8> {
    if let Some(fcc) = tag.audio_fourcc {
        let packet_type = tag.ex_packet_type.unwrap_or(AUDIO_PACKET_TYPE_CODED_FRAMES);
        // When a ModEx prelude is present the header byte's
        // AudioPacketType nibble is `ModEx`; the real packet type is
        // carried by the terminating nibble of the chain
        // (enhanced-rtmp-v2.pdf §"ExAudioTagHeader").
        let header_pt = if tag.mod_ex.is_empty() {
            packet_type
        } else {
            AUDIO_PACKET_TYPE_MOD_EX
        };
        let head = (AUDIO_FORMAT_EX_HEADER << 4) | (header_pt & 0x0F);
        let mut out = Vec::with_capacity(tag.body.len() + 5);
        out.push(head);
        build_mod_ex_chain(&mut out, &tag.mod_ex, AUDIO_PACKET_TYPE_MOD_EX, packet_type);
        out.extend_from_slice(&fcc);
        out.extend_from_slice(&tag.body);
        out
    } else {
        let b0 = (tag.sound_format << 4)
            | ((tag.sound_rate & 0x03) << 2)
            | (if tag.sound_size_16bit { 0x02 } else { 0 })
            | (if tag.stereo { 0x01 } else { 0 });
        let mut out = Vec::with_capacity(tag.body.len() + 2);
        out.push(b0);
        if tag.sound_format == AUDIO_FORMAT_AAC {
            out.push(tag.aac_packet_type.unwrap_or(AAC_PACKET_TYPE_RAW));
        }
        out.extend_from_slice(&tag.body);
        out
    }
}

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

    #[test]
    fn video_tag_avc_nalu_roundtrip() {
        let tag = VideoTag {
            mod_ex: Vec::new(),
            frame_type: VIDEO_FRAME_KEYFRAME,
            codec_id: VIDEO_CODEC_AVC,
            avc_packet_type: Some(AVC_PACKET_TYPE_NALU),
            composition_time: 42,
            body: b"\x00\x00\x00\x05hello".to_vec(),
            ex_packet_type: None,
            fourcc: None,
        };
        let payload = build_video(&tag);
        assert_eq!(payload[0], 0x17); // keyframe + AVC
        let back = parse_video(&payload).unwrap();
        assert_eq!(back, tag);
    }

    #[test]
    fn video_tag_negative_cts_sign_extends() {
        let tag = VideoTag {
            mod_ex: Vec::new(),
            frame_type: VIDEO_FRAME_INTER,
            codec_id: VIDEO_CODEC_AVC,
            avc_packet_type: Some(AVC_PACKET_TYPE_NALU),
            composition_time: -5,
            body: vec![0x01],
            ex_packet_type: None,
            fourcc: None,
        };
        let payload = build_video(&tag);
        let back = parse_video(&payload).unwrap();
        assert_eq!(back.composition_time, -5);
    }

    // ------- Enhanced RTMP v1 (Veovera 2023) round-trips -------

    #[test]
    fn ex_video_tag_hevc_sequence_start_roundtrip() {
        // SequenceStart: HEVCDecoderConfigurationRecord in body,
        // no SI24 CTS on the wire.
        let tag = VideoTag {
            mod_ex: Vec::new(),
            frame_type: VIDEO_FRAME_KEYFRAME,
            codec_id: 0,
            avc_packet_type: None,
            composition_time: 0,
            body: b"\x01dummy-hvcc".to_vec(),
            ex_packet_type: Some(EX_PACKET_TYPE_SEQUENCE_START),
            fourcc: Some(FOURCC_HEVC),
        };
        let payload = build_video(&tag);
        // Header byte: IsExHeader(1) | FrameType(001) | PacketType(0000)
        // = 0b1001_0000 = 0x90.
        assert_eq!(payload[0], 0x90);
        assert_eq!(&payload[1..5], b"hvc1");
        // No SI24 between FourCC and body for SequenceStart.
        assert_eq!(&payload[5..], b"\x01dummy-hvcc");

        let back = parse_video(&payload).unwrap();
        assert_eq!(back, tag);
        assert!(back.is_ex_sequence_header());
        assert!(back.is_keyframe());
    }

    #[test]
    fn ex_video_tag_hevc_coded_frames_carries_cts() {
        // CodedFrames is the only Enhanced RTMP shape that
        // keeps the SI24 CTS on the wire (per Table 4's HEVC
        // pseudocode).
        let tag = VideoTag {
            mod_ex: Vec::new(),
            frame_type: VIDEO_FRAME_INTER,
            codec_id: 0,
            avc_packet_type: None,
            composition_time: -33,
            body: b"\x00\x00\x00\x04NALU".to_vec(),
            ex_packet_type: Some(EX_PACKET_TYPE_CODED_FRAMES),
            fourcc: Some(FOURCC_HEVC),
        };
        let payload = build_video(&tag);
        // IsExHeader=1 | FrameType=2 | PacketType=1 = 0b1010_0001 = 0xA1.
        assert_eq!(payload[0], 0xA1);
        assert_eq!(&payload[1..5], b"hvc1");
        // SI24(-33) two's complement = 0xFFFFDF; truncated to
        // 24 bits = 0xFFFFDF — three bytes 0xFF 0xFF 0xDF.
        assert_eq!(&payload[5..8], &[0xFF, 0xFF, 0xDF]);
        assert_eq!(&payload[8..], b"\x00\x00\x00\x04NALU");

        let back = parse_video(&payload).unwrap();
        assert_eq!(back, tag);
        assert_eq!(back.composition_time, -33);
    }

    #[test]
    fn ex_video_tag_hevc_coded_frames_x_omits_cts() {
        // CodedFramesX is the SI24=0 optimisation — three
        // bytes off the wire vs CodedFrames.
        let tag = VideoTag {
            mod_ex: Vec::new(),
            frame_type: VIDEO_FRAME_INTER,
            codec_id: 0,
            avc_packet_type: None,
            composition_time: 0,
            body: b"\x00\x00\x00\x04NALU".to_vec(),
            ex_packet_type: Some(EX_PACKET_TYPE_CODED_FRAMES_X),
            fourcc: Some(FOURCC_HEVC),
        };
        let payload = build_video(&tag);
        // IsExHeader=1 | FrameType=2 | PacketType=3 = 0xA3.
        assert_eq!(payload[0], 0xA3);
        assert_eq!(&payload[1..5], b"hvc1");
        // Body follows the FourCC directly — no SI24 bytes.
        assert_eq!(&payload[5..], b"\x00\x00\x00\x04NALU");
        // Total length saved is exactly 3 bytes vs the
        // CodedFrames form (1-byte header + 4-byte FourCC +
        // 8-byte body, no SI24).
        assert_eq!(payload.len(), 1 + 4 + 8);

        let back = parse_video(&payload).unwrap();
        assert_eq!(back, tag);
    }

    #[test]
    fn ex_video_tag_av1_sequence_start_no_cts() {
        // AV1 SequenceStart body is the
        // AV1CodecConfigurationRecord (per spec). No CTS.
        let tag = VideoTag {
            mod_ex: Vec::new(),
            frame_type: VIDEO_FRAME_KEYFRAME,
            codec_id: 0,
            avc_packet_type: None,
            composition_time: 0,
            body: b"\x81\x05\x0c\x00".to_vec(),
            ex_packet_type: Some(EX_PACKET_TYPE_SEQUENCE_START),
            fourcc: Some(FOURCC_AV1),
        };
        let payload = build_video(&tag);
        assert_eq!(payload[0], 0x90);
        assert_eq!(&payload[1..5], b"av01");
        assert_eq!(&payload[5..], b"\x81\x05\x0c\x00");

        let back = parse_video(&payload).unwrap();
        assert_eq!(back, tag);
        assert!(back.is_ex_sequence_header());
    }

    #[test]
    fn ex_video_tag_av1_coded_frames_obus() {
        // AV1 CodedFrames body is "one or more OBUs which MUST
        // represent a single temporal unit" (Enhanced RTMP v1
        // §"If FourCC == AV1"). Still no CTS — only HEVC keeps
        // composition-time on the wire.
        let tag = VideoTag {
            mod_ex: Vec::new(),
            frame_type: VIDEO_FRAME_KEYFRAME,
            codec_id: 0,
            avc_packet_type: None,
            composition_time: 0,
            body: b"\x0a\x0b\x0cobu-stub".to_vec(),
            ex_packet_type: Some(EX_PACKET_TYPE_CODED_FRAMES),
            fourcc: Some(FOURCC_AV1),
        };
        let payload = build_video(&tag);
        // IsExHeader=1 | FrameType=1 | PacketType=1 = 0x91.
        assert_eq!(payload[0], 0x91);
        assert_eq!(&payload[1..5], b"av01");
        // Body immediately follows FourCC (no SI24 for AV1).
        assert_eq!(&payload[5..], b"\x0a\x0b\x0cobu-stub");

        let back = parse_video(&payload).unwrap();
        assert_eq!(back, tag);
    }

    #[test]
    fn ex_video_tag_vp9_coded_frames_full_frame() {
        // VP9 CodedFrames body "MUST contain full frames"
        // (Enhanced RTMP v1 §"If FourCC == VP9").
        let tag = VideoTag {
            mod_ex: Vec::new(),
            frame_type: VIDEO_FRAME_KEYFRAME,
            codec_id: 0,
            avc_packet_type: None,
            composition_time: 0,
            body: b"vp9-frame-bytes".to_vec(),
            ex_packet_type: Some(EX_PACKET_TYPE_CODED_FRAMES),
            fourcc: Some(FOURCC_VP9),
        };
        let payload = build_video(&tag);
        assert_eq!(payload[0], 0x91);
        assert_eq!(&payload[1..5], b"vp09");
        assert_eq!(&payload[5..], b"vp9-frame-bytes");

        let back = parse_video(&payload).unwrap();
        assert_eq!(back, tag);
    }

    #[test]
    fn ex_video_tag_sequence_end_empty_body() {
        // SequenceEnd carries no codec data — body is empty.
        let tag = VideoTag {
            mod_ex: Vec::new(),
            frame_type: VIDEO_FRAME_KEYFRAME,
            codec_id: 0,
            avc_packet_type: None,
            composition_time: 0,
            body: vec![],
            ex_packet_type: Some(EX_PACKET_TYPE_SEQUENCE_END),
            fourcc: Some(FOURCC_HEVC),
        };
        let payload = build_video(&tag);
        // IsExHeader=1 | FrameType=1 | PacketType=2 = 0x92.
        assert_eq!(payload[0], 0x92);
        assert_eq!(&payload[1..5], b"hvc1");
        assert_eq!(payload.len(), 5);

        let back = parse_video(&payload).unwrap();
        assert_eq!(back, tag);
    }

    #[test]
    fn ex_video_tag_metadata_carries_amf_body() {
        // PacketTypeMetadata: body is an AMF-encoded `[name,
        // value]` pair (only `"colorInfo"` is defined in v1).
        // Spec says: "presence of PacketTypeMetadata means
        // that FrameType flags at the top of this table should
        // be ignored." We still preserve the bits — caller
        // policy decides.
        let tag = VideoTag {
            mod_ex: Vec::new(),
            frame_type: VIDEO_FRAME_INFO, // would be "ignored" per spec
            codec_id: 0,
            avc_packet_type: None,
            composition_time: 0,
            body: b"amf-stub".to_vec(),
            ex_packet_type: Some(EX_PACKET_TYPE_METADATA),
            fourcc: Some(FOURCC_HEVC),
        };
        let payload = build_video(&tag);
        // IsExHeader=1 | FrameType=5 | PacketType=4 = 0xD4.
        assert_eq!(payload[0], 0xD4);
        let back = parse_video(&payload).unwrap();
        assert_eq!(back, tag);
        assert!(back.is_ex_metadata());
    }

    #[test]
    fn legacy_avc_high_frame_type_bit_was_always_zero() {
        // Sanity-check the Enhanced RTMP backwards-compat
        // claim: pre-2023 FrameType values 1..=5 all leave bit
        // 7 of the header byte clear, so a parser that branches
        // on IsExHeader == 1 never mis-detects legacy traffic
        // as Enhanced.
        for ft in [
            VIDEO_FRAME_KEYFRAME,
            VIDEO_FRAME_INTER,
            VIDEO_FRAME_DISPOSABLE,
            VIDEO_FRAME_GENERATED_KEY,
            VIDEO_FRAME_INFO,
        ] {
            let tag = VideoTag {
                mod_ex: Vec::new(),
                frame_type: ft,
                codec_id: VIDEO_CODEC_AVC,
                avc_packet_type: Some(AVC_PACKET_TYPE_NALU),
                composition_time: 0,
                body: vec![0x00],
                ex_packet_type: None,
                fourcc: None,
            };
            let payload = build_video(&tag);
            assert_eq!(payload[0] & VIDEO_IS_EX_HEADER, 0, "ft={ft}");
        }
    }

    // ------- Enhanced RTMP v2 (Veovera 2026) new video FourCCs -------

    #[test]
    fn ex_video_tag_vp8_sequence_start_carries_vp_config_record() {
        // VP8 SequenceStart body is a `VPCodecConfigurationRecord`
        // (same shape as VP9 — per enhanced-rtmp-v2.pdf §"Enhanced
        // Video" the pseudocode is `vp8Header =
        // [VPCodecConfigurationRecord]`). No CTS — VP8 has no
        // B-frames.
        let tag = VideoTag {
            mod_ex: Vec::new(),
            frame_type: VIDEO_FRAME_KEYFRAME,
            codec_id: 0,
            avc_packet_type: None,
            composition_time: 0,
            body: vec![
                0x01, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            ],
            ex_packet_type: Some(EX_PACKET_TYPE_SEQUENCE_START),
            fourcc: Some(FOURCC_VP8),
        };
        let payload = build_video(&tag);
        // IsExHeader=1 | FrameType=1 (key) | PacketType=0 = 0x90.
        assert_eq!(payload[0], 0x90);
        assert_eq!(&payload[1..5], b"vp08");
        assert_eq!(&payload[5..], &tag.body[..]);

        let back = parse_video(&payload).unwrap();
        assert_eq!(back, tag);
        assert!(back.is_ex_sequence_header());
    }

    #[test]
    fn ex_video_tag_vp8_coded_frames_no_cts() {
        // VP8 CodedFrames body is one or more full frames; no CTS
        // on the wire (no B-frame ordering).
        let tag = VideoTag {
            mod_ex: Vec::new(),
            frame_type: VIDEO_FRAME_INTER,
            codec_id: 0,
            avc_packet_type: None,
            composition_time: 0,
            body: b"vp8-frame-bytes".to_vec(),
            ex_packet_type: Some(EX_PACKET_TYPE_CODED_FRAMES),
            fourcc: Some(FOURCC_VP8),
        };
        let payload = build_video(&tag);
        // IsExHeader=1 | FrameType=2 | PacketType=1 = 0xA1.
        assert_eq!(payload[0], 0xA1);
        assert_eq!(&payload[1..5], b"vp08");
        // Body immediately follows FourCC — no SI24 phantom.
        assert_eq!(&payload[5..], b"vp8-frame-bytes");
        let back = parse_video(&payload).unwrap();
        assert_eq!(back, tag);
    }

    #[test]
    fn ex_video_tag_avc_fourcc_sequence_start_carries_avcc() {
        // FourCC-mode AVC SequenceStart body is the
        // `AVCDecoderConfigurationRecord` (per ISO/IEC 14496-15
        // §5.3.4.1, cited verbatim by enhanced-rtmp-v2.pdf
        // §"Enhanced Video"). No CTS on SequenceStart for any
        // FourCC, AVC included.
        let tag = VideoTag {
            mod_ex: Vec::new(),
            frame_type: VIDEO_FRAME_KEYFRAME,
            codec_id: 0,
            avc_packet_type: None,
            composition_time: 0,
            body: b"\x01\x42\xc0\x1edummy-avcc".to_vec(),
            ex_packet_type: Some(EX_PACKET_TYPE_SEQUENCE_START),
            fourcc: Some(FOURCC_AVC),
        };
        let payload = build_video(&tag);
        // IsExHeader=1 | FrameType=1 | PacketType=0 = 0x90.
        assert_eq!(payload[0], 0x90);
        assert_eq!(&payload[1..5], b"avc1");
        // No SI24 — body follows FourCC directly.
        assert_eq!(&payload[5..], b"\x01\x42\xc0\x1edummy-avcc");
        let back = parse_video(&payload).unwrap();
        assert_eq!(back, tag);
        assert!(back.is_ex_sequence_header());
    }

    #[test]
    fn ex_video_tag_avc_fourcc_coded_frames_carries_si24_cts() {
        // FourCC-mode AVC CodedFrames carries SI24
        // `compositionTimeOffset` exactly like HEVC. Tested with a
        // negative offset (-100) to also exercise the sign-extend
        // path through both build and parse.
        let tag = VideoTag {
            mod_ex: Vec::new(),
            frame_type: VIDEO_FRAME_INTER,
            codec_id: 0,
            avc_packet_type: None,
            composition_time: -100,
            body: b"\x00\x00\x00\x05nalu1".to_vec(),
            ex_packet_type: Some(EX_PACKET_TYPE_CODED_FRAMES),
            fourcc: Some(FOURCC_AVC),
        };
        let payload = build_video(&tag);
        // IsExHeader=1 | FrameType=2 | PacketType=1 = 0xA1.
        assert_eq!(payload[0], 0xA1);
        assert_eq!(&payload[1..5], b"avc1");
        // SI24(-100) = 0xFFFF9C two's complement.
        assert_eq!(&payload[5..8], &[0xFF, 0xFF, 0x9C]);
        assert_eq!(&payload[8..], b"\x00\x00\x00\x05nalu1");
        let back = parse_video(&payload).unwrap();
        assert_eq!(back, tag);
        assert_eq!(back.composition_time, -100);
    }

    #[test]
    fn ex_video_tag_avc_fourcc_coded_frames_x_omits_cts() {
        // CodedFramesX optimisation — same as HEVC: no SI24 on the
        // wire, three bytes saved.
        let tag = VideoTag {
            mod_ex: Vec::new(),
            frame_type: VIDEO_FRAME_INTER,
            codec_id: 0,
            avc_packet_type: None,
            composition_time: 0,
            body: b"\x00\x00\x00\x05nalu2".to_vec(),
            ex_packet_type: Some(EX_PACKET_TYPE_CODED_FRAMES_X),
            fourcc: Some(FOURCC_AVC),
        };
        let payload = build_video(&tag);
        // IsExHeader=1 | FrameType=2 | PacketType=3 = 0xA3.
        assert_eq!(payload[0], 0xA3);
        assert_eq!(&payload[1..5], b"avc1");
        // Body follows immediately — no SI24.
        assert_eq!(&payload[5..], b"\x00\x00\x00\x05nalu2");
        assert_eq!(payload.len(), 1 + 4 + 9);
        let back = parse_video(&payload).unwrap();
        assert_eq!(back, tag);
    }

    #[test]
    fn ex_video_tag_vvc_sequence_start_carries_vvcc() {
        // VVC SequenceStart body is `VVCDecoderConfigurationRecord`
        // (per ISO/IEC 14496-15:2024 §11.2.4.2). No CTS on
        // SequenceStart.
        let tag = VideoTag {
            mod_ex: Vec::new(),
            frame_type: VIDEO_FRAME_KEYFRAME,
            codec_id: 0,
            avc_packet_type: None,
            composition_time: 0,
            body: b"\xff\xfcdummy-vvcc".to_vec(),
            ex_packet_type: Some(EX_PACKET_TYPE_SEQUENCE_START),
            fourcc: Some(FOURCC_VVC),
        };
        let payload = build_video(&tag);
        assert_eq!(payload[0], 0x90);
        assert_eq!(&payload[1..5], b"vvc1");
        assert_eq!(&payload[5..], b"\xff\xfcdummy-vvcc");
        let back = parse_video(&payload).unwrap();
        assert_eq!(back, tag);
        assert!(back.is_ex_sequence_header());
    }

    #[test]
    fn ex_video_tag_vvc_coded_frames_carries_si24_cts() {
        // VVC CodedFrames carries SI24 like HEVC and AVC — covers
        // the §"ExVideoTagBody" pseudocode `if (videoFourCc ==
        // VideoFourCc.Vvc) { compositionTimeOffset = SI24 }`.
        let tag = VideoTag {
            mod_ex: Vec::new(),
            frame_type: VIDEO_FRAME_KEYFRAME,
            codec_id: 0,
            avc_packet_type: None,
            composition_time: 17,
            body: b"\x00\x00\x00\x06h266ku".to_vec(),
            ex_packet_type: Some(EX_PACKET_TYPE_CODED_FRAMES),
            fourcc: Some(FOURCC_VVC),
        };
        let payload = build_video(&tag);
        // IsExHeader=1 | FrameType=1 | PacketType=1 = 0x91.
        assert_eq!(payload[0], 0x91);
        assert_eq!(&payload[1..5], b"vvc1");
        // SI24(17) = 0x000011.
        assert_eq!(&payload[5..8], &[0x00, 0x00, 0x11]);
        assert_eq!(&payload[8..], b"\x00\x00\x00\x06h266ku");
        let back = parse_video(&payload).unwrap();
        assert_eq!(back, tag);
        assert_eq!(back.composition_time, 17);
    }

    #[test]
    fn ex_video_tag_vvc_coded_frames_x_omits_cts() {
        let tag = VideoTag {
            mod_ex: Vec::new(),
            frame_type: VIDEO_FRAME_INTER,
            codec_id: 0,
            avc_packet_type: None,
            composition_time: 0,
            body: b"\x00\x00\x00\x03vvc".to_vec(),
            ex_packet_type: Some(EX_PACKET_TYPE_CODED_FRAMES_X),
            fourcc: Some(FOURCC_VVC),
        };
        let payload = build_video(&tag);
        // IsExHeader=1 | FrameType=2 | PacketType=3 = 0xA3.
        assert_eq!(payload[0], 0xA3);
        assert_eq!(&payload[1..5], b"vvc1");
        assert_eq!(&payload[5..], b"\x00\x00\x00\x03vvc");
        let back = parse_video(&payload).unwrap();
        assert_eq!(back, tag);
    }

    #[test]
    fn ex_video_tag_avc_fourcc_coded_frames_truncated_si24_errors() {
        // §"ExVideoTagBody" guarantees the SI24 follows the
        // FourCC for AVC + CodedFrames. A wire stream missing
        // those three bytes must fail in a controlled manner
        // per "the system MUST fail in a controlled and
        // predictable manner".
        let truncated = [
            0xA1, // IsExHeader=1 | FrameType=2 | PacketType=1
            b'a', b'v', b'c', b'1', // FourCC
            0xFF, 0xFF, // only two of three SI24 bytes
        ];
        assert!(parse_video(&truncated).is_err());
    }

    #[test]
    fn ex_video_tag_v2_fourccs_are_distinct_from_v1_set() {
        // Wire-byte distinctness check: each v2 FourCC must
        // round-trip independently of the v1 set so a multiplexer
        // can't accidentally alias one to another.
        for &fcc in &[FOURCC_VP8, FOURCC_AVC, FOURCC_VVC] {
            let tag = VideoTag {
                mod_ex: Vec::new(),
                frame_type: VIDEO_FRAME_KEYFRAME,
                codec_id: 0,
                avc_packet_type: None,
                composition_time: 0,
                body: vec![0xDE, 0xAD, 0xBE, 0xEF],
                ex_packet_type: Some(EX_PACKET_TYPE_SEQUENCE_END),
                fourcc: Some(fcc),
            };
            let payload = build_video(&tag);
            // SequenceEnd: ExHeader byte + FourCC, no body
            // expected, but we ship a stub for the round-trip
            // check.
            assert_eq!(&payload[1..5], &fcc[..]);
            let back = parse_video(&payload).unwrap();
            assert_eq!(back, tag);
            assert!(!matches!(fcc, FOURCC_AV1 | FOURCC_VP9 | FOURCC_HEVC));
        }
    }

    #[test]
    fn audio_tag_aac_sequence_header_roundtrip() {
        let tag = AudioTag {
            mod_ex: Vec::new(),
            sound_format: AUDIO_FORMAT_AAC,
            sound_rate: 3,
            sound_size_16bit: true,
            stereo: true,
            aac_packet_type: Some(AAC_PACKET_TYPE_SEQUENCE_HEADER),
            body: vec![0x12, 0x10], // LC-AAC 44.1k stereo AudioSpecificConfig
            ex_packet_type: None,
            audio_fourcc: None,
        };
        let payload = build_audio(&tag);
        assert_eq!(payload[0], 0xAF); // AAC + rate 3 + 16-bit + stereo
        assert_eq!(payload[1], 0); // seq header
        let back = parse_audio(&payload).unwrap();
        assert_eq!(back, tag);
        assert!(back.is_aac_sequence_header());
        assert!(!back.is_enhanced());
    }

    // ------- Enhanced RTMP v2 (Veovera 2026) round-trips -------

    #[test]
    fn ex_audio_tag_opus_sequence_start_roundtrip() {
        // SequenceStart for Opus: body is the Opus ID header (a
        // valid one starts with the 8-byte "OpusHead" magic per
        // RFC 7845 §5.1; we use a tiny stub here since the
        // framing layer doesn't validate codec-payload internals).
        let tag = AudioTag {
            mod_ex: Vec::new(),
            sound_format: AUDIO_FORMAT_EX_HEADER,
            sound_rate: 0,
            sound_size_16bit: false,
            stereo: false,
            aac_packet_type: None,
            ex_packet_type: Some(AUDIO_PACKET_TYPE_SEQUENCE_START),
            audio_fourcc: Some(FOURCC_OPUS),
            body: b"OpusHead\x01\x02".to_vec(),
        };
        let payload = build_audio(&tag);
        // Header byte: ExHeader(9) << 4 | PacketType(0) = 0x90.
        assert_eq!(payload[0], 0x90);
        assert_eq!(&payload[1..5], b"Opus");
        assert_eq!(&payload[5..], b"OpusHead\x01\x02");

        let back = parse_audio(&payload).unwrap();
        assert_eq!(back, tag);
        assert!(back.is_ex_sequence_header());
        assert!(back.is_enhanced());
        // Legacy bit-field is suppressed in Enhanced mode.
        assert_eq!(back.sound_rate, 0);
        assert!(!back.sound_size_16bit);
        assert!(!back.stereo);
    }

    #[test]
    fn ex_audio_tag_opus_coded_frames_carries_self_delimited_packets() {
        // Enhanced RTMP v2: "Body contains Opus packets [...] The
        // first (N - 1) Opus packets, if any, are packed one after
        // another using the self-delimiting framing from Appendix
        // B of [RFC6716]. The remaining Opus packet is packed at
        // the end of the Ogg packet using the regular,
        // undelimited framing from Section 3 of [RFC6716]." The
        // framing layer treats the body as opaque bytes.
        let tag = AudioTag {
            mod_ex: Vec::new(),
            sound_format: AUDIO_FORMAT_EX_HEADER,
            sound_rate: 0,
            sound_size_16bit: false,
            stereo: false,
            aac_packet_type: None,
            ex_packet_type: Some(AUDIO_PACKET_TYPE_CODED_FRAMES),
            audio_fourcc: Some(FOURCC_OPUS),
            body: b"opus-frame-bytes".to_vec(),
        };
        let payload = build_audio(&tag);
        // ExHeader=9 | CodedFrames=1 = 0x91.
        assert_eq!(payload[0], 0x91);
        assert_eq!(&payload[1..5], b"Opus");
        assert_eq!(&payload[5..], b"opus-frame-bytes");

        let back = parse_audio(&payload).unwrap();
        assert_eq!(back, tag);
    }

    #[test]
    fn ex_audio_tag_flac_sequence_start_roundtrip() {
        // FLAC SequenceStart body: "The bytes 0x66 0x4C 0x61 0x43
        // ('fLaC' in ASCII) signature // Followed by a metadata
        // block (called the STREAMINFO block) as described in
        // section 7 of the FLAC specification." The framing layer
        // treats this as opaque.
        let tag = AudioTag {
            mod_ex: Vec::new(),
            sound_format: AUDIO_FORMAT_EX_HEADER,
            sound_rate: 0,
            sound_size_16bit: false,
            stereo: false,
            aac_packet_type: None,
            ex_packet_type: Some(AUDIO_PACKET_TYPE_SEQUENCE_START),
            audio_fourcc: Some(FOURCC_FLAC),
            body: b"fLaC\x80\x00\x00\x22streaminfo".to_vec(),
        };
        let payload = build_audio(&tag);
        assert_eq!(payload[0], 0x90);
        assert_eq!(&payload[1..5], b"fLaC");
        assert_eq!(&payload[5..], b"fLaC\x80\x00\x00\x22streaminfo");

        let back = parse_audio(&payload).unwrap();
        assert_eq!(back, tag);
        assert!(back.is_ex_sequence_header());
    }

    #[test]
    fn ex_audio_tag_ac3_coded_frames_roundtrip() {
        // AC-3: "Body contains audio data as defined by the
        // bitstream syntax in the ATSC standard for Digital Audio
        // Compression (AC-3, E-AC-3)." No SequenceStart shape is
        // defined for AC-3 in v2 — only CodedFrames carries data.
        let tag = AudioTag {
            mod_ex: Vec::new(),
            sound_format: AUDIO_FORMAT_EX_HEADER,
            sound_rate: 0,
            sound_size_16bit: false,
            stereo: false,
            aac_packet_type: None,
            ex_packet_type: Some(AUDIO_PACKET_TYPE_CODED_FRAMES),
            audio_fourcc: Some(FOURCC_AC3),
            body: vec![0x0B, 0x77, 0x12, 0x34, 0x56, 0x78], // AC-3 sync + stub
        };
        let payload = build_audio(&tag);
        assert_eq!(payload[0], 0x91);
        assert_eq!(&payload[1..5], b"ac-3");
        assert_eq!(&payload[5..], &[0x0B, 0x77, 0x12, 0x34, 0x56, 0x78]);

        let back = parse_audio(&payload).unwrap();
        assert_eq!(back, tag);
    }

    #[test]
    fn ex_audio_tag_eac3_coded_frames_roundtrip() {
        let tag = AudioTag {
            mod_ex: Vec::new(),
            sound_format: AUDIO_FORMAT_EX_HEADER,
            sound_rate: 0,
            sound_size_16bit: false,
            stereo: false,
            aac_packet_type: None,
            ex_packet_type: Some(AUDIO_PACKET_TYPE_CODED_FRAMES),
            audio_fourcc: Some(FOURCC_EAC3),
            body: vec![0x0B, 0x77, 0xAB, 0xCD],
        };
        let payload = build_audio(&tag);
        assert_eq!(payload[0], 0x91);
        assert_eq!(&payload[1..5], b"ec-3");
        let back = parse_audio(&payload).unwrap();
        assert_eq!(back, tag);
    }

    #[test]
    fn ex_audio_tag_mp3_coded_frames_roundtrip() {
        // MP3 (added FOURCC signalling): "An Mp3 audio stream is
        // built up from a succession of smaller parts called
        // frames. Each frame is a data block with its own header
        // and audio information."
        let tag = AudioTag {
            mod_ex: Vec::new(),
            sound_format: AUDIO_FORMAT_EX_HEADER,
            sound_rate: 0,
            sound_size_16bit: false,
            stereo: false,
            aac_packet_type: None,
            ex_packet_type: Some(AUDIO_PACKET_TYPE_CODED_FRAMES),
            audio_fourcc: Some(FOURCC_MP3),
            body: vec![0xFF, 0xFB, 0x90, 0x00], // MP3 sync header stub
        };
        let payload = build_audio(&tag);
        assert_eq!(payload[0], 0x91);
        assert_eq!(&payload[1..5], b".mp3");
        let back = parse_audio(&payload).unwrap();
        assert_eq!(back, tag);
    }

    #[test]
    fn ex_audio_tag_aac_fourcc_sequence_start() {
        // AAC with FourCC signalling is the v2 way to carry AAC
        // alongside the other FourCC codecs. Body for
        // SequenceStart is AudioSpecificConfig per ISO/IEC
        // 14496-3 — same shape as the legacy AacSequenceHeader,
        // but reached via FourCC instead of the legacy
        // SoundFormat=10 / AACPacketType=0 path.
        let tag = AudioTag {
            mod_ex: Vec::new(),
            sound_format: AUDIO_FORMAT_EX_HEADER,
            sound_rate: 0,
            sound_size_16bit: false,
            stereo: false,
            aac_packet_type: None,
            ex_packet_type: Some(AUDIO_PACKET_TYPE_SEQUENCE_START),
            audio_fourcc: Some(FOURCC_AAC),
            body: vec![0x12, 0x10], // LC-AAC 44.1k stereo ASC
        };
        let payload = build_audio(&tag);
        assert_eq!(payload[0], 0x90);
        assert_eq!(&payload[1..5], b"mp4a");
        assert_eq!(&payload[5..], &[0x12, 0x10]);

        let back = parse_audio(&payload).unwrap();
        assert_eq!(back, tag);
        assert!(back.is_ex_sequence_header());
        // The legacy `is_aac_sequence_header` predicate stays
        // false because the legacy SoundFormat/AacPacketType
        // discriminator isn't on the wire.
        assert!(!back.is_aac_sequence_header());
    }

    #[test]
    fn ex_audio_tag_sequence_end_empty_body() {
        let tag = AudioTag {
            mod_ex: Vec::new(),
            sound_format: AUDIO_FORMAT_EX_HEADER,
            sound_rate: 0,
            sound_size_16bit: false,
            stereo: false,
            aac_packet_type: None,
            ex_packet_type: Some(AUDIO_PACKET_TYPE_SEQUENCE_END),
            audio_fourcc: Some(FOURCC_OPUS),
            body: vec![],
        };
        let payload = build_audio(&tag);
        // ExHeader=9 | SequenceEnd=2 = 0x92.
        assert_eq!(payload[0], 0x92);
        assert_eq!(&payload[1..5], b"Opus");
        assert_eq!(payload.len(), 5);

        let back = parse_audio(&payload).unwrap();
        assert_eq!(back, tag);
    }

    #[test]
    fn ex_audio_tag_truncated_fourcc_errors() {
        // ExHeader byte alone is not enough — the FourCC follows.
        // Per spec, the parser MUST fail in a controlled manner.
        let truncated = [0x90, b'O', b'p', b'u']; // missing one byte of FourCC
        assert!(parse_audio(&truncated).is_err());
        let just_header = [0x90];
        assert!(parse_audio(&just_header).is_err());
    }

    #[test]
    fn legacy_audio_high_nibble_never_collides_with_ex_header() {
        // Sanity-check the v2 backwards-compatibility claim:
        // every legacy SoundFormat value lies outside
        // {9 = ExHeader}, so a parser branching on
        // `sound_format == ExHeader` never mis-detects a legacy
        // tag as Enhanced.
        for sf in [
            AUDIO_FORMAT_PCM_LE,
            AUDIO_FORMAT_ADPCM,
            AUDIO_FORMAT_MP3,
            AUDIO_FORMAT_PCM_LE_8BIT,
            AUDIO_FORMAT_NELLYMOSER_16K_MONO,
            AUDIO_FORMAT_NELLYMOSER_8K_MONO,
            AUDIO_FORMAT_NELLYMOSER,
            AUDIO_FORMAT_G711_ALAW,
            AUDIO_FORMAT_G711_MULAW,
            AUDIO_FORMAT_AAC,
            AUDIO_FORMAT_SPEEX,
        ] {
            assert_ne!(sf, AUDIO_FORMAT_EX_HEADER, "sf={sf}");
        }
    }

    // ------- Enhanced RTMP v2 ModEx prelude (Veovera 2026) -------

    #[test]
    fn ex_video_mod_ex_timestamp_offset_nano_roundtrip() {
        // A single TimestampOffsetNano ModEx entry preceding a VVC
        // CodedFrames packet. Header byte low nibble = ModEx(7);
        // chain carries the real CodedFrames(1) packet type in its
        // terminating nibble; SI24 CTS then follows the FourCC.
        let nano = 999_999u32; // spec max sub-millisecond offset.
        let tag = VideoTag {
            frame_type: VIDEO_FRAME_INTER,
            codec_id: 0,
            avc_packet_type: None,
            composition_time: 7,
            body: b"\x00\x00\x00\x05nalu!".to_vec(),
            ex_packet_type: Some(EX_PACKET_TYPE_CODED_FRAMES),
            fourcc: Some(FOURCC_VVC),
            mod_ex: vec![ModEx::timestamp_offset_nano_entry(nano)],
        };
        let payload = build_video(&tag);
        // byte 0 = IsExHeader|FrameType(2)|ModEx(7) = 0b1010_0111 = 0xA7.
        assert_eq!(payload[0], 0xA7);
        // modExDataSize = UI8 + 1 → data is 3 bytes, so UI8 = 2.
        assert_eq!(payload[1], 2);
        // modExData = bytesToUI24(999_999) = 0x0F_423F.
        assert_eq!(&payload[2..5], &[0x0F, 0x42, 0x3F]);
        // nibble byte: modExType(0, high) | packetType CodedFrames(1, low).
        assert_eq!(payload[5], 0x01);
        // FourCC then SI24 CTS then body.
        assert_eq!(&payload[6..10], b"vvc1");
        assert_eq!(&payload[10..13], &[0x00, 0x00, 0x07]);
        assert_eq!(&payload[13..], b"\x00\x00\x00\x05nalu!");

        let back = parse_video(&payload).unwrap();
        assert_eq!(back, tag);
        assert_eq!(back.timestamp_offset_nano(), nano);
        assert_eq!(back.mod_ex[0].timestamp_offset_nano(), Some(nano));
    }

    #[test]
    fn ex_video_mod_ex_chain_multiple_entries_roundtrip() {
        // Two chained ModEx entries before an AV1 SequenceStart.
        // The first entry's terminating nibble is ModEx again; the
        // second's is the real SequenceStart(0).
        let tag = VideoTag {
            frame_type: VIDEO_FRAME_KEYFRAME,
            codec_id: 0,
            avc_packet_type: None,
            composition_time: 0,
            body: b"av1cfg".to_vec(),
            ex_packet_type: Some(EX_PACKET_TYPE_SEQUENCE_START),
            fourcc: Some(FOURCC_AV1),
            mod_ex: vec![
                ModEx::timestamp_offset_nano_entry(500_000),
                ModEx {
                    mod_ex_type: 3, // a future/unknown subtype: preserved verbatim
                    data: vec![0xAA, 0xBB],
                },
            ],
        };
        let payload = build_video(&tag);
        // First entry: size byte (2 → 3-byte data), data, nibble
        // (ModExType 0 | ModEx 7) = 0x07.
        assert_eq!(payload[1], 2);
        assert_eq!(&payload[2..5], &[0x07, 0xA1, 0x20]); // bytesToUI24(500_000)
        assert_eq!(payload[5], 0x07);
        // Second entry: size byte (1 → 2-byte data), data, nibble
        // (ModExType 3 | SequenceStart 0) = 0x30.
        assert_eq!(payload[6], 1);
        assert_eq!(&payload[7..9], &[0xAA, 0xBB]);
        assert_eq!(payload[9], 0x30);
        assert_eq!(&payload[10..14], b"av01");
        assert_eq!(&payload[14..], b"av1cfg");

        let back = parse_video(&payload).unwrap();
        assert_eq!(back, tag);
        // Only the TimestampOffsetNano entry contributes to the sum.
        assert_eq!(back.timestamp_offset_nano(), 500_000);
    }

    #[test]
    fn ex_video_mod_ex_ui16_size_escape_roundtrip() {
        // modExData longer than 255 bytes uses the UI16 escape:
        // the 8-bit size byte is 0xFF (== 256 sentinel) followed by
        // a UI16 of (len - 1).
        let big = vec![0x5A; 300];
        let tag = VideoTag {
            frame_type: VIDEO_FRAME_INTER,
            codec_id: 0,
            avc_packet_type: None,
            composition_time: 0,
            body: b"hevc-frame".to_vec(),
            ex_packet_type: Some(EX_PACKET_TYPE_CODED_FRAMES_X),
            fourcc: Some(FOURCC_HEVC),
            mod_ex: vec![ModEx {
                mod_ex_type: MOD_EX_TYPE_TIMESTAMP_OFFSET_NANO,
                data: big.clone(),
            }],
        };
        let payload = build_video(&tag);
        // size: 0xFF sentinel + UI16(len-1 = 299 = 0x012B).
        assert_eq!(payload[1], 0xFF);
        assert_eq!(&payload[2..4], &[0x01, 0x2B]);
        assert_eq!(&payload[4..4 + 300], &big[..]);
        // nibble after data: ModExType 0 | CodedFramesX(3).
        assert_eq!(payload[4 + 300], 0x03);

        let back = parse_video(&payload).unwrap();
        assert_eq!(back, tag);
        assert_eq!(back.mod_ex[0].data.len(), 300);
    }

    #[test]
    fn ex_audio_mod_ex_timestamp_offset_nano_roundtrip() {
        // ModEx prelude on an Opus CodedFrames audio tag.
        let nano = 250_000u32;
        let tag = AudioTag {
            sound_format: AUDIO_FORMAT_EX_HEADER,
            sound_rate: 0,
            sound_size_16bit: false,
            stereo: false,
            aac_packet_type: None,
            ex_packet_type: Some(AUDIO_PACKET_TYPE_CODED_FRAMES),
            audio_fourcc: Some(FOURCC_OPUS),
            body: b"opus-pkt".to_vec(),
            mod_ex: vec![ModEx::timestamp_offset_nano_entry(nano)],
        };
        let payload = build_audio(&tag);
        // byte 0 = ExHeader(9) << 4 | ModEx(7) = 0x97.
        assert_eq!(payload[0], 0x97);
        assert_eq!(payload[1], 2); // 3-byte data → UI8 = 2.
        assert_eq!(&payload[2..5], &[0x03, 0xD0, 0x90]); // bytesToUI24(250_000)
                                                         // nibble: ModExType 0 | CodedFrames(1).
        assert_eq!(payload[5], 0x01);
        assert_eq!(&payload[6..10], b"Opus");
        assert_eq!(&payload[10..], b"opus-pkt");

        let back = parse_audio(&payload).unwrap();
        assert_eq!(back, tag);
        assert_eq!(back.timestamp_offset_nano(), nano);
    }

    #[test]
    fn mod_ex_accessor_rejects_wrong_type_and_short_data() {
        // timestamp_offset_nano() only resolves for the
        // TimestampOffsetNano subtype with >= 3 data bytes.
        let wrong_type = ModEx {
            mod_ex_type: 1,
            data: vec![0, 0, 0],
        };
        assert_eq!(wrong_type.timestamp_offset_nano(), None);
        let too_short = ModEx {
            mod_ex_type: MOD_EX_TYPE_TIMESTAMP_OFFSET_NANO,
            data: vec![0x00, 0x01],
        };
        assert_eq!(too_short.timestamp_offset_nano(), None);
    }

    #[test]
    fn ex_video_mod_ex_truncated_chain_fails_controlled() {
        // Header announces ModEx but the chain is cut short — the
        // parser must surface a controlled error, not panic / index
        // out of bounds.
        // byte0 = IsExHeader|FrameType1|ModEx7 = 0x97 then a size
        // byte claiming 3 data bytes but no data following.
        let truncated = [0x97u8, 0x02];
        assert!(parse_video(&truncated).is_err());
        // Size + data present but missing the modExType/packetType nibble.
        let no_nibble = [0x97u8, 0x02, 0x00, 0x00, 0x00];
        assert!(parse_video(&no_nibble).is_err());
        // Chain terminates with a real packet type but no FourCC.
        let no_fourcc = [0x97u8, 0x02, 0x00, 0x00, 0x00, 0x01];
        assert!(parse_video(&no_fourcc).is_err());
    }

    #[test]
    fn ex_audio_mod_ex_truncated_chain_fails_controlled() {
        let truncated = [0x97u8, 0x02];
        assert!(parse_audio(&truncated).is_err());
        let no_fourcc = [0x97u8, 0x02, 0x00, 0x00, 0x00, 0x01];
        assert!(parse_audio(&no_fourcc).is_err());
    }

    #[test]
    fn ex_video_without_mod_ex_emits_no_prelude() {
        // Empty mod_ex must produce byte-identical output to the
        // pre-ModEx encoding (no spurious prelude bytes).
        let tag = VideoTag {
            frame_type: VIDEO_FRAME_KEYFRAME,
            codec_id: 0,
            avc_packet_type: None,
            composition_time: 0,
            body: b"\x01cfg".to_vec(),
            ex_packet_type: Some(EX_PACKET_TYPE_SEQUENCE_START),
            fourcc: Some(FOURCC_HEVC),
            mod_ex: Vec::new(),
        };
        let payload = build_video(&tag);
        // Header low nibble is the real packet type, not ModEx.
        assert_eq!(payload[0] & 0x0F, EX_PACKET_TYPE_SEQUENCE_START);
        assert_eq!(&payload[1..5], b"hvc1");
        assert_eq!(&payload[5..], b"\x01cfg");
        assert_eq!(parse_video(&payload).unwrap(), tag);
    }
}