arcly-stream 0.1.6

An open-extensible live-media streaming kernel: lock-free zero-copy frame fan-out, instant-start GOP cache, a pluggable multi-protocol ingestion layer (RTMP, RTSP, SRT, WHIP/WHEP shipped), and a feature-gated pure-Rust media plane (MPEG-TS/HLS/fMP4) — runtime, config, and metrics free.
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
//! Shared RTP/RTCP parsing and NAL-codec (de)packetization — RFC 3550 framing
//! plus H.264 (RFC 6184) and H.265 (RFC 7798) payload formats.
//!
//! Gated behind the internal `_rtp` marker, pulled in by both [`rtsp`] and
//! [`webrtc`]. The two transports differ only in how RTP packets reach the
//! process (TCP-interleaved / UDP for RTSP, DTLS-SRTP for WebRTC); once a packet
//! is in hand, reassembling NAL units into an Annex-B access unit is identical,
//! so it lives here once.
//!
//! [`rtsp`]: crate::protocol::rtsp
//! [`webrtc`]: crate::protocol::webrtc
//!
//! # What it does
//!
//! - [`RtpHeader::parse`] decodes the fixed RTP header (RFC 3550 §5.1), honoring
//!   the CSRC count and the extension-header flag to locate the payload.
//! - [`H264Depacketizer`] / [`H265Depacketizer`] turn a sequence of RTP payloads
//!   into complete access units in Annex-B form. Each handles the three NALU
//!   packetization modes for its codec — single NAL, aggregation (STAP-A type 24
//!   / AP type 48), and fragmentation (FU-A type 28 / FU type 49) — emitting an
//!   access unit when the marker bit is set or the timestamp advances.
//! - [`RtpPacketizer`] performs the reverse for egress (e.g. WebRTC WHEP),
//!   selecting the H.264 or H.265 payload format.
//!
//! # What it does not do
//!
//! Jitter-buffer reordering and loss concealment are the caller's concern — the
//! depacketizer assumes in-order delivery (true for TCP-interleaved RTSP; for
//! UDP/SRTP a small reorder buffer should sit in front of it). It reports a
//! [`DepacketizeError::OutOfOrder`] gap so a handler can request a keyframe
//! (PLI/FIR) rather than emit a corrupt access unit.

use bytes::Bytes;

/// Annex-B start code prefixed to every reassembled NAL unit.
const ANNEXB_START: [u8; 4] = [0, 0, 0, 1];

/// A parsed RTP fixed header (RFC 3550 §5.1).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RtpHeader {
    /// Payload type (7 bits) — identifies the codec/format binding from SDP.
    pub payload_type: u8,
    /// Marker bit. For H.264 it flags the last packet of an access unit.
    pub marker: bool,
    /// 16-bit sequence number, increments by one per packet (wraps).
    pub sequence: u16,
    /// 32-bit media timestamp in the payload's clock (90 kHz for H.264 video).
    pub timestamp: u32,
    /// Synchronization source identifier.
    pub ssrc: u32,
    /// Byte offset at which the payload begins (past CSRCs and any extension).
    pub payload_offset: usize,
}

impl RtpHeader {
    /// Parse the fixed header from the front of `buf`, returning the header and
    /// the payload offset. Returns `None` if `buf` is too short or the version
    /// field is not 2.
    pub fn parse(buf: &[u8]) -> Option<RtpHeader> {
        use super::byteops::ByteReader;
        let mut r = ByteReader::new(buf);
        let b0 = r.u8()?;
        if b0 >> 6 != 2 {
            return None; // RTP version must be 2
        }
        let has_extension = b0 & 0x10 != 0;
        let csrc_count = (b0 & 0x0F) as usize;
        let b1 = r.u8()?;
        let marker = b1 & 0x80 != 0;
        let payload_type = b1 & 0x7F;
        let sequence = r.u16_be()?;
        let timestamp = r.u32_be()?;
        let ssrc = r.u32_be()?;
        r.skip(csrc_count * 4)?; // CSRC list

        if has_extension {
            // Extension header: 2-byte profile id, 2-byte length (in 32-bit words).
            r.skip(2)?;
            let ext_words = r.u16_be()? as usize;
            r.skip(ext_words * 4)?;
        }
        Some(RtpHeader {
            payload_type,
            marker,
            sequence,
            timestamp,
            ssrc,
            payload_offset: r.position(),
        })
    }
}

/// Errors surfaced while depacketizing an RTP stream.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum DepacketizeError {
    /// The packet was shorter than the format requires.
    Truncated,
    /// A sequence-number discontinuity was detected mid-fragment; the partial
    /// access unit was dropped. The handler should request a keyframe.
    OutOfOrder,
    /// An unsupported NAL/aggregation type was encountered.
    Unsupported(u8),
}

/// Depacketizes RFC 3640 AAC-hbr RTP payloads into raw AAC access units.
///
/// The common RTSP/SDP profile for AAC (`mode=AAC-hbr`, `sizelength=13`,
/// `indexlength=3`) frames each payload as a 2-byte **AU-headers-length** (in
/// bits), followed by one 2-byte AU-header per access unit (13-bit size +
/// 3-bit index), followed by the access units concatenated. One RTP packet may
/// carry several AAC frames; [`push`](Self::push) returns each as a separate
/// raw (ADTS-less) [`bytes::Bytes`].
#[derive(Debug, Clone, Copy, Default)]
pub struct AacDepacketizer {
    /// Bits per AU-header `size` field (13 for AAC-hbr).
    size_length: u8,
    /// Bits per AU-header `index`/`index-delta` field (3 for AAC-hbr).
    index_length: u8,
}

impl AacDepacketizer {
    /// A depacketizer for the standard AAC-hbr profile (`sizelength=13`,
    /// `indexlength=3`).
    pub fn new() -> Self {
        Self {
            size_length: 13,
            index_length: 3,
        }
    }

    /// A depacketizer with explicit AU-header field widths from the SDP `fmtp`.
    pub fn with_lengths(size_length: u8, index_length: u8) -> Self {
        Self {
            size_length,
            index_length,
        }
    }

    /// Split one RTP AAC-hbr payload into its constituent access units.
    pub fn push(&self, payload: &[u8]) -> Result<Vec<Bytes>, DepacketizeError> {
        if payload.len() < 2 {
            return Err(DepacketizeError::Truncated);
        }
        // Sizes wider than a 16-bit AU-header field are unsupported (and would
        // otherwise over-shift below). `with_lengths` can supply arbitrary widths.
        if self.size_length == 0 || self.size_length > 16 {
            return Err(DepacketizeError::Unsupported(self.size_length));
        }
        let header_bits = u16::from_be_bytes([payload[0], payload[1]]) as usize;
        let au_header_bits = self.size_length as usize + self.index_length as usize;
        if au_header_bits == 0 {
            return Err(DepacketizeError::Unsupported(0));
        }
        let header_bytes = header_bits.div_ceil(8);
        let au_count = header_bits / au_header_bits;
        let headers = payload
            .get(2..2 + header_bytes)
            .ok_or(DepacketizeError::Truncated)?;
        let mut data_off = 2 + header_bytes;
        let mut out = Vec::with_capacity(au_count);
        for i in 0..au_count {
            // Each AU-header is `au_header_bits` wide; for AAC-hbr that is 16
            // bits, so the size is the top `size_length` bits of a 2-byte field.
            let bit = i * au_header_bits;
            let byte = bit / 8;
            let hdr = headers
                .get(byte..byte + 2)
                .ok_or(DepacketizeError::Truncated)?;
            let size = (u16::from_be_bytes([hdr[0], hdr[1]]) >> (16 - self.size_length)) as usize;
            let end = data_off + size;
            let au = payload
                .get(data_off..end)
                .ok_or(DepacketizeError::Truncated)?;
            out.push(Bytes::copy_from_slice(au));
            data_off = end;
        }
        Ok(out)
    }
}

/// Packetizes H.264 Annex-B access units into RFC 6184 RTP packets — the inverse
/// of [`H264Depacketizer`], used for WebRTC/WHEP egress.
///
/// Each NAL unit that fits the MTU is sent as a single-NAL packet; larger NALs
/// are split into FU-A fragments. The RTP marker bit is set on the last packet
/// of each access unit so the receiver knows the frame is complete.
#[derive(Debug, Clone)]
pub struct RtpPacketizer {
    payload_type: u8,
    ssrc: u32,
    sequence: u16,
    /// Maximum RTP payload size (excluding the 12-byte header).
    max_payload: usize,
    /// Which NAL-based RTP payload format to emit (H.264 RFC 6184 vs H.265
    /// RFC 7798 — they differ in NAL-header width and FU framing).
    codec: NalCodec,
}

/// The NAL-based codecs [`RtpPacketizer`] / the depacketizers understand. Both
/// are Annex-B start-code framed; they differ in NAL-header width (1 vs 2 bytes)
/// and fragmentation-unit layout.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum NalCodec {
    H264,
    H265,
}

impl RtpPacketizer {
    /// An H.264 packetizer for `payload_type`/`ssrc`. `mtu` is the maximum UDP
    /// payload (1200 is the WebRTC-safe default); the 12-byte RTP header is
    /// subtracted.
    pub fn new(payload_type: u8, ssrc: u32, mtu: usize) -> Self {
        Self::with_codec(payload_type, ssrc, mtu, NalCodec::H264)
    }

    /// An H.265 (HEVC) packetizer, emitting the RFC 7798 payload format
    /// (2-byte NAL header, FU type 49). Counterpart to [`new`](Self::new).
    pub fn new_h265(payload_type: u8, ssrc: u32, mtu: usize) -> Self {
        Self::with_codec(payload_type, ssrc, mtu, NalCodec::H265)
    }

    fn with_codec(payload_type: u8, ssrc: u32, mtu: usize, codec: NalCodec) -> Self {
        Self {
            payload_type,
            ssrc,
            sequence: 0,
            max_payload: mtu.saturating_sub(12).max(1),
            codec,
        }
    }

    /// Build the 12-byte RTP header for the next packet and advance the sequence.
    fn header(&mut self, marker: bool, timestamp: u32, out: &mut Vec<u8>) {
        write_rtp_header(
            out,
            self.payload_type,
            marker,
            self.sequence,
            timestamp,
            self.ssrc,
        );
        self.sequence = self.sequence.wrapping_add(1);
    }

    /// Packetize one Annex-B access unit at `timestamp` (90 kHz) into RTP packets.
    ///
    /// Each NAL that fits the MTU is sent as a single-NAL packet; larger NALs are
    /// fragmented (FU-A for H.264, FU for H.265). The marker bit is set on the
    /// last packet of the access unit.
    pub fn packetize(&mut self, access_unit: &[u8], timestamp: u32) -> Vec<Vec<u8>> {
        // Both codecs are Annex-B start-code framed; the shared scanner yields the
        // NAL units (without start codes) in order.
        let nals: Vec<&[u8]> = crate::codec::nal::iter_nals(access_unit)
            .filter(|n| !n.is_empty())
            .collect();
        let mut packets = Vec::new();
        for (i, nal) in nals.iter().enumerate() {
            let last_nal = i + 1 == nals.len();
            if nal.len() <= self.max_payload {
                // Single NAL unit packet; marker on the final NAL of the AU.
                let mut pkt = Vec::with_capacity(12 + nal.len());
                self.header(last_nal, timestamp, &mut pkt);
                pkt.extend_from_slice(nal);
                packets.push(pkt);
            } else {
                match self.codec {
                    NalCodec::H264 => self.fragment_fua(nal, timestamp, last_nal, &mut packets),
                    NalCodec::H265 => self.fragment_fu_h265(nal, timestamp, last_nal, &mut packets),
                }
            }
        }
        packets
    }

    /// Split one oversized NAL into FU-A fragments (RFC 6184 §5.8).
    fn fragment_fua(&mut self, nal: &[u8], timestamp: u32, last_nal: bool, out: &mut Vec<Vec<u8>>) {
        let nal_header = nal[0];
        let fu_indicator = (nal_header & 0xE0) | 28; // F|NRI from NAL, type 28
        let nal_type = nal_header & 0x1F;
        let body = &nal[1..];
        // Each fragment carries a 2-byte FU header (indicator + FU header).
        let chunk = self.max_payload.saturating_sub(2).max(1);
        let n_chunks = body.len().div_ceil(chunk);
        for (idx, part) in body.chunks(chunk).enumerate() {
            let start = idx == 0;
            let end = idx + 1 == n_chunks;
            let mut fu_header = nal_type;
            if start {
                fu_header |= 0x80;
            }
            if end {
                fu_header |= 0x40;
            }
            let mut pkt = Vec::with_capacity(12 + 2 + part.len());
            // Marker only on the very last fragment of the final NAL of the AU.
            self.header(last_nal && end, timestamp, &mut pkt);
            pkt.push(fu_indicator);
            pkt.push(fu_header);
            pkt.extend_from_slice(part);
            out.push(pkt);
        }
    }

    /// Split one oversized H.265 NAL into FU fragments (RFC 7798 §4.4.3).
    ///
    /// The 2-byte NAL header becomes a PayloadHdr with its type field set to 49
    /// (the F/LayerId/TID bits are preserved); each fragment then carries a
    /// 1-byte FU header (`S | E | FuType`) where `FuType` is the original type.
    fn fragment_fu_h265(
        &mut self,
        nal: &[u8],
        timestamp: u32,
        last_nal: bool,
        out: &mut Vec<Vec<u8>>,
    ) {
        // A well-formed H.265 NAL has a 2-byte header; anything shorter can't be
        // fragmented meaningfully, so emit it as a single packet.
        if nal.len() < 2 {
            let mut pkt = Vec::with_capacity(12 + nal.len());
            self.header(last_nal, timestamp, &mut pkt);
            pkt.extend_from_slice(nal);
            out.push(pkt);
            return;
        }
        let nal_type = (nal[0] >> 1) & 0x3F;
        // PayloadHdr: keep F (bit 15) + LayerId + TID, overwrite the 6-bit type
        // field with 49 (FU). Type occupies bits 9..14, i.e. (byte0 >> 1) & 0x3F.
        let payload_hdr0 = (nal[0] & 0x81) | (49 << 1);
        let payload_hdr1 = nal[1];
        let body = &nal[2..];
        // Each fragment carries the 2-byte PayloadHdr + 1-byte FU header.
        let chunk = self.max_payload.saturating_sub(3).max(1);
        let n_chunks = body.len().div_ceil(chunk);
        for (idx, part) in body.chunks(chunk).enumerate() {
            let start = idx == 0;
            let end = idx + 1 == n_chunks;
            let mut fu_header = nal_type;
            if start {
                fu_header |= 0x80;
            }
            if end {
                fu_header |= 0x40;
            }
            let mut pkt = Vec::with_capacity(12 + 3 + part.len());
            self.header(last_nal && end, timestamp, &mut pkt);
            pkt.push(payload_hdr0);
            pkt.push(payload_hdr1);
            pkt.push(fu_header);
            pkt.extend_from_slice(part);
            out.push(pkt);
        }
    }
}

/// Reassembles RFC 6184 H.264 RTP payloads into Annex-B access units.
///
/// Feed each packet's payload (the bytes after [`RtpHeader::payload_offset`])
/// with its marker bit and timestamp to [`push`](Self::push). When a complete
/// access unit is ready the method returns `Ok(Some(au))`, where `au` is the
/// concatenated NAL units each prefixed with a 4-byte Annex-B start code —
/// exactly the shape the codec parsers and `annexb_to_avcc` expect.
#[derive(Debug, Default)]
pub struct H264Depacketizer {
    /// Bytes accumulated for the current access unit (Annex-B framed).
    au: Vec<u8>,
    /// FU-A reassembly buffer for the NAL currently being defragmented.
    fua: Vec<u8>,
    /// `true` while an FU-A fragment is in progress (between Start and End bits).
    in_fragment: bool,
    /// Reconstructed NAL header byte for the in-progress FU-A NAL.
    fua_header: u8,
    /// Timestamp of the access unit currently being assembled.
    current_ts: Option<u32>,
    /// Last sequence number seen (for gap detection during fragmentation).
    last_seq: Option<u16>,
}

impl H264Depacketizer {
    /// A fresh depacketizer with no in-progress access unit.
    pub fn new() -> Self {
        Self::default()
    }

    /// Append one NAL unit (Annex-B framed) to the current access unit.
    fn append_nal(&mut self, nal: &[u8]) {
        self.au.extend_from_slice(&ANNEXB_START);
        self.au.extend_from_slice(nal);
    }

    /// Whether the pending access unit holds an IDR (type 5) NAL — a keyframe.
    fn pending_is_keyframe(&self) -> bool {
        // Scan the assembled Annex-B for a NAL header with type 5.
        let mut i = 0;
        while i + 4 < self.au.len() {
            if self.au[i..i + 4] == ANNEXB_START {
                let nal_type = self.au[i + 4] & 0x1F;
                if nal_type == 5 {
                    return true;
                }
            }
            i += 1;
        }
        false
    }

    /// Emit and reset the pending access unit, if any.
    fn take_au(&mut self) -> Option<AccessUnit> {
        if self.au.is_empty() {
            return None;
        }
        let keyframe = self.pending_is_keyframe();
        let timestamp = self.current_ts.unwrap_or(0);
        let data = Bytes::from(std::mem::take(&mut self.au));
        self.current_ts = None;
        Some(AccessUnit {
            data,
            timestamp,
            keyframe,
        })
    }

    /// Push one RTP H.264 payload. Returns a completed [`AccessUnit`] when the
    /// marker bit closes the frame (or the timestamp advances to a new one).
    pub fn push(
        &mut self,
        payload: &[u8],
        marker: bool,
        timestamp: u32,
        sequence: u16,
    ) -> Result<Option<AccessUnit>, DepacketizeError> {
        if payload.is_empty() {
            return Err(DepacketizeError::Truncated);
        }

        // A timestamp change flushes the previous access unit before starting the
        // new one (some encoders omit the marker bit).
        let mut completed = None;
        if let Some(ts) = self.current_ts {
            if ts != timestamp && !self.in_fragment {
                completed = self.take_au();
            }
        }
        self.current_ts = Some(timestamp);

        let nal_type = payload[0] & 0x1F;
        match nal_type {
            1..=23 => {
                // Single NAL unit packet — the payload *is* the NAL.
                self.append_nal(payload);
            }
            24 => {
                // STAP-A: one byte type, then [u16 size][nal]… aggregates.
                let mut i = 1;
                while i + 2 <= payload.len() {
                    let size = u16::from_be_bytes([payload[i], payload[i + 1]]) as usize;
                    i += 2;
                    if i + size > payload.len() {
                        return Err(DepacketizeError::Truncated);
                    }
                    self.append_nal(&payload[i..i + size]);
                    i += size;
                }
            }
            28 => {
                // FU-A: byte0 = FU indicator, byte1 = FU header (S|E|R|type).
                if payload.len() < 2 {
                    return Err(DepacketizeError::Truncated);
                }
                let fu_header = payload[1];
                let start = fu_header & 0x80 != 0;
                let end = fu_header & 0x40 != 0;
                let frag_type = fu_header & 0x1F;

                if start {
                    // Reconstruct the original NAL header: F|NRI from the indicator,
                    // type from the FU header.
                    self.fua_header = (payload[0] & 0xE0) | frag_type;
                    self.fua.clear();
                    self.fua.push(self.fua_header);
                    self.in_fragment = true;
                } else if !self.in_fragment {
                    // Mid/last fragment with no start — lost the head.
                    return Err(DepacketizeError::OutOfOrder);
                } else if self.seq_gap(sequence) {
                    self.in_fragment = false;
                    self.fua.clear();
                    return Err(DepacketizeError::OutOfOrder);
                }
                self.fua.extend_from_slice(&payload[2..]);

                if end && self.in_fragment {
                    let nal = std::mem::take(&mut self.fua);
                    self.append_nal(&nal);
                    self.in_fragment = false;
                }
            }
            other => return Err(DepacketizeError::Unsupported(other)),
        }

        self.last_seq = Some(sequence);

        if completed.is_some() {
            return Ok(completed);
        }
        if marker {
            return Ok(self.take_au());
        }
        Ok(None)
    }

    /// Detect a one-step sequence-number gap relative to the previous packet.
    fn seq_gap(&self, sequence: u16) -> bool {
        match self.last_seq {
            Some(prev) => sequence.wrapping_sub(prev) != 1,
            None => false,
        }
    }
}

/// Reassembles RFC 7798 H.265 (HEVC) RTP payloads into Annex-B access units.
///
/// The H.265 counterpart to [`H264Depacketizer`], used for ingesting HEVC IP
/// cameras and encoders over RTSP/WebRTC. It handles the three packetization
/// modes: single NAL units, aggregation packets (AP, type 48), and fragmentation
/// units (FU, type 49). The output shape — NAL units each prefixed with a 4-byte
/// Annex-B start code — matches [`H264Depacketizer`] and the codec parsers.
///
/// DONL/DOND fields (only present when `sprop-max-don-diff > 0` is negotiated in
/// SDP) are not consumed; the common single-stream profile does not use them.
#[derive(Debug, Default)]
pub struct H265Depacketizer {
    /// Bytes accumulated for the current access unit (Annex-B framed).
    au: Vec<u8>,
    /// FU reassembly buffer for the NAL currently being defragmented.
    fu: Vec<u8>,
    /// `true` while an FU is in progress (between Start and End bits).
    in_fragment: bool,
    /// Timestamp of the access unit currently being assembled.
    current_ts: Option<u32>,
    /// Last sequence number seen (for gap detection during fragmentation).
    last_seq: Option<u16>,
}

impl H265Depacketizer {
    /// A fresh depacketizer with no in-progress access unit.
    pub fn new() -> Self {
        Self::default()
    }

    /// Append one NAL unit (Annex-B framed) to the current access unit.
    fn append_nal(&mut self, nal: &[u8]) {
        self.au.extend_from_slice(&ANNEXB_START);
        self.au.extend_from_slice(nal);
    }

    /// Whether the pending access unit holds an IRAP (BLA/IDR/CRA, types 16–23)
    /// VCL NAL — i.e. a random-access point / keyframe.
    fn pending_is_keyframe(&self) -> bool {
        let mut i = 0;
        while i + 4 < self.au.len() {
            if self.au[i..i + 4] == ANNEXB_START {
                let nal_type = (self.au[i + 4] >> 1) & 0x3F;
                if (16..=23).contains(&nal_type) {
                    return true;
                }
            }
            i += 1;
        }
        false
    }

    /// Emit and reset the pending access unit, if any.
    fn take_au(&mut self) -> Option<AccessUnit> {
        if self.au.is_empty() {
            return None;
        }
        let keyframe = self.pending_is_keyframe();
        let timestamp = self.current_ts.unwrap_or(0);
        let data = Bytes::from(std::mem::take(&mut self.au));
        self.current_ts = None;
        Some(AccessUnit {
            data,
            timestamp,
            keyframe,
        })
    }

    /// Detect a one-step sequence-number gap relative to the previous packet.
    fn seq_gap(&self, sequence: u16) -> bool {
        match self.last_seq {
            Some(prev) => sequence.wrapping_sub(prev) != 1,
            None => false,
        }
    }

    /// Push one RTP H.265 payload. Returns a completed [`AccessUnit`] when the
    /// marker bit closes the frame (or the timestamp advances to a new one).
    pub fn push(
        &mut self,
        payload: &[u8],
        marker: bool,
        timestamp: u32,
        sequence: u16,
    ) -> Result<Option<AccessUnit>, DepacketizeError> {
        // The H.265 NAL header is two bytes; a single byte cannot carry a type.
        if payload.len() < 2 {
            return Err(DepacketizeError::Truncated);
        }

        // A timestamp change flushes the previous access unit (some encoders omit
        // the marker bit).
        let mut completed = None;
        if let Some(ts) = self.current_ts {
            if ts != timestamp && !self.in_fragment {
                completed = self.take_au();
            }
        }
        self.current_ts = Some(timestamp);

        let nal_type = (payload[0] >> 1) & 0x3F;
        match nal_type {
            // Single NAL unit packet — the payload *is* the NAL (header included).
            0..=47 => self.append_nal(payload),
            48 => {
                // AP: 2-byte header, then [u16 size][nal]… aggregates.
                let mut i = 2;
                while i + 2 <= payload.len() {
                    let size = u16::from_be_bytes([payload[i], payload[i + 1]]) as usize;
                    i += 2;
                    if i + size > payload.len() {
                        return Err(DepacketizeError::Truncated);
                    }
                    self.append_nal(&payload[i..i + size]);
                    i += size;
                }
            }
            49 => {
                // FU: 2-byte PayloadHdr, 1-byte FU header (S|E|FuType), then body.
                if payload.len() < 3 {
                    return Err(DepacketizeError::Truncated);
                }
                let fu_header = payload[2];
                let start = fu_header & 0x80 != 0;
                let end = fu_header & 0x40 != 0;
                let fu_type = fu_header & 0x3F;

                if start {
                    // Reconstruct the original 2-byte NAL header: restore the type
                    // field (bits 9..14) from FuType, keep F/LayerId/TID.
                    let hdr0 = (payload[0] & 0x81) | (fu_type << 1);
                    let hdr1 = payload[1];
                    self.fu.clear();
                    self.fu.push(hdr0);
                    self.fu.push(hdr1);
                    self.in_fragment = true;
                } else if !self.in_fragment {
                    return Err(DepacketizeError::OutOfOrder);
                } else if self.seq_gap(sequence) {
                    self.in_fragment = false;
                    self.fu.clear();
                    return Err(DepacketizeError::OutOfOrder);
                }
                self.fu.extend_from_slice(&payload[3..]);

                if end && self.in_fragment {
                    let nal = std::mem::take(&mut self.fu);
                    self.append_nal(&nal);
                    self.in_fragment = false;
                }
            }
            other => return Err(DepacketizeError::Unsupported(other)),
        }

        self.last_seq = Some(sequence);

        if completed.is_some() {
            return Ok(completed);
        }
        if marker {
            return Ok(self.take_au());
        }
        Ok(None)
    }
}

/// A reassembled coded video frame from the RTP bus.
///
/// For the NAL codecs (H.264/H.265) `data` is the access unit in Annex-B form
/// (each NAL prefixed with a 4-byte start code); for VP9/AV1 it is the raw coded
/// frame / temporal unit. `keyframe` marks a decodable random-access point.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AccessUnit {
    /// The coded frame bytes (Annex-B NALs for H.26x; raw frame for VP9/AV1).
    pub data: Bytes,
    /// RTP media timestamp (90 kHz) of the frame.
    pub timestamp: u32,
    /// Whether this is a keyframe / random-access point.
    pub keyframe: bool,
}

/// Write the 12-byte RTP fixed header (V=2, no padding/extension/CSRC) for one
/// packet. Shared by every packetizer in this module.
fn write_rtp_header(out: &mut Vec<u8>, pt: u8, marker: bool, seq: u16, ts: u32, ssrc: u32) {
    out.push(0x80); // V=2, P=0, X=0, CC=0
    out.push(if marker { 0x80 } else { 0 } | (pt & 0x7F));
    out.extend_from_slice(&seq.to_be_bytes());
    out.extend_from_slice(&ts.to_be_bytes());
    out.extend_from_slice(&ssrc.to_be_bytes());
}

// ── VP9 (draft-ietf-payload-vp9) ─────────────────────────────────────────────

/// Packetizes VP9 coded frames into RTP, using a flexible-mode-off payload
/// descriptor for the common single-layer (non-scalable) case.
///
/// Each frame is carried verbatim after a VP9 payload descriptor (the bytes are
/// not transformed — VP9 RTP carries the frame opaquely), split across the MTU
/// with the B (begin) bit on the first packet and E (end) + RTP marker on the
/// last. A 15-bit picture ID increments per frame. Spatial/temporal scalability
/// and flexible mode are out of scope.
#[derive(Debug, Clone)]
pub struct Vp9Packetizer {
    payload_type: u8,
    ssrc: u32,
    sequence: u16,
    max_payload: usize,
    picture_id: u16,
}

impl Vp9Packetizer {
    /// A VP9 packetizer for `payload_type`/`ssrc`. `mtu` is the maximum UDP
    /// payload; the 12-byte RTP header and a 3-byte descriptor are subtracted.
    pub fn new(payload_type: u8, ssrc: u32, mtu: usize) -> Self {
        Self {
            payload_type,
            ssrc,
            sequence: 0,
            // 12-byte RTP header + up to 3-byte descriptor (1 flags + 2 picture id).
            max_payload: mtu.saturating_sub(12 + 3).max(1),
            picture_id: 0,
        }
    }

    /// Packetize one VP9 frame at `timestamp` (90 kHz). `keyframe` clears the P
    /// (inter-predicted) bit so receivers can identify random-access points.
    pub fn packetize(&mut self, frame: &[u8], timestamp: u32, keyframe: bool) -> Vec<Vec<u8>> {
        let pid = self.picture_id & 0x7FFF;
        self.picture_id = self.picture_id.wrapping_add(1);

        let mut packets = Vec::new();
        let chunks: Vec<&[u8]> = if frame.is_empty() {
            vec![&[]]
        } else {
            frame.chunks(self.max_payload).collect()
        };
        let n = chunks.len();
        for (i, chunk) in chunks.into_iter().enumerate() {
            let begin = i == 0;
            let end = i + 1 == n;
            let mut pkt = Vec::with_capacity(12 + 3 + chunk.len());
            write_rtp_header(
                &mut pkt,
                self.payload_type,
                end,
                self.sequence,
                timestamp,
                self.ssrc,
            );
            self.sequence = self.sequence.wrapping_add(1);

            // Descriptor octet: I=1, P=!keyframe, L=0, F=0, B, E, V=0, Z=0.
            let mut desc0 = 0x80; // I = 1 (picture ID present)
            if !keyframe {
                desc0 |= 0x40; // P (inter-predicted)
            }
            if begin {
                desc0 |= 0x08; // B (start of frame)
            }
            if end {
                desc0 |= 0x04; // E (end of frame)
            }
            pkt.push(desc0);
            // 15-bit picture ID (M=1): 0x80|hi, lo.
            pkt.push(0x80 | (pid >> 8) as u8);
            pkt.push((pid & 0xFF) as u8);
            pkt.extend_from_slice(chunk);
            packets.push(pkt);
        }
        packets
    }
}

/// Reassembles VP9 RTP payloads (draft-ietf-payload-vp9, non-flexible single
/// layer) into coded frames. Counterpart to [`Vp9Packetizer`].
#[derive(Debug, Default)]
pub struct Vp9Depacketizer {
    frame: Vec<u8>,
    in_frame: bool,
    keyframe: bool,
    current_ts: Option<u32>,
}

impl Vp9Depacketizer {
    /// A fresh depacketizer with no in-progress frame.
    pub fn new() -> Self {
        Self::default()
    }

    /// Push one VP9 RTP payload. Returns a completed frame when the E (end) bit
    /// and RTP marker close it.
    pub fn push(
        &mut self,
        payload: &[u8],
        marker: bool,
        timestamp: u32,
    ) -> Result<Option<AccessUnit>, DepacketizeError> {
        if payload.is_empty() {
            return Err(DepacketizeError::Truncated);
        }
        let desc0 = payload[0];
        let has_pid = desc0 & 0x80 != 0;
        let has_layer = desc0 & 0x20 != 0;
        let flexible = desc0 & 0x10 != 0;
        let begin = desc0 & 0x08 != 0;
        let end = desc0 & 0x04 != 0;
        let predicted = desc0 & 0x40 != 0;

        // Walk past the variable-length descriptor fields we recognize.
        let mut off = 1;
        if has_pid {
            // M bit selects a 1- or 2-byte picture ID.
            let m = payload.get(off).ok_or(DepacketizeError::Truncated)? & 0x80 != 0;
            off += if m { 2 } else { 1 };
        }
        if has_layer {
            off += 1; // TID/U/SID/D byte
            if !flexible {
                off += 1; // TL0PICIDX (non-flexible mode)
            }
        }
        if off > payload.len() {
            return Err(DepacketizeError::Truncated);
        }

        if begin {
            self.frame.clear();
            self.in_frame = true;
            self.keyframe = !predicted;
            self.current_ts = Some(timestamp);
        } else if !self.in_frame {
            return Err(DepacketizeError::OutOfOrder);
        }
        self.frame.extend_from_slice(&payload[off..]);

        if end && marker && self.in_frame {
            self.in_frame = false;
            return Ok(Some(AccessUnit {
                data: Bytes::from(std::mem::take(&mut self.frame)),
                timestamp: self.current_ts.unwrap_or(timestamp),
                keyframe: self.keyframe,
            }));
        }
        Ok(None)
    }
}

// ── AV1 (AOMedia "RTP Payload Format For AV1") ───────────────────────────────

/// Encode `v` as unsigned LEB128 into `out`.
#[cfg(feature = "codec-av1")]
fn leb128_encode(mut v: u64, out: &mut Vec<u8>) {
    loop {
        let mut byte = (v & 0x7F) as u8;
        v >>= 7;
        if v != 0 {
            byte |= 0x80;
        }
        out.push(byte);
        if v == 0 {
            break;
        }
    }
}

const AV1_OBU_SEQUENCE_HEADER: u8 = 1;
const AV1_OBU_TEMPORAL_DELIMITER: u8 = 2;

/// Packetizes an AV1 temporal unit into RTP using the AOMedia payload format.
///
/// Each non-temporal-delimiter OBU is re-framed as a length-delimited *OBU
/// element* (the W=0 form, with the OBU's `obu_has_size_field` cleared), the
/// elements are concatenated, and the resulting stream is split across the MTU
/// with a one-byte aggregation header per packet (Z/Y continuation bits, N on a
/// new coded video sequence). The temporal delimiter is dropped per the spec;
/// frame boundaries are conveyed by the RTP marker. Scalability structures are
/// not emitted.
#[cfg(feature = "codec-av1")]
#[derive(Debug, Clone)]
pub struct Av1Packetizer {
    payload_type: u8,
    ssrc: u32,
    sequence: u16,
    max_payload: usize,
}

#[cfg(feature = "codec-av1")]
impl Av1Packetizer {
    /// An AV1 packetizer for `payload_type`/`ssrc`. `mtu` is the maximum UDP
    /// payload; the 12-byte RTP header and 1-byte aggregation header are removed.
    pub fn new(payload_type: u8, ssrc: u32, mtu: usize) -> Self {
        Self {
            payload_type,
            ssrc,
            sequence: 0,
            max_payload: mtu.saturating_sub(12 + 1).max(1),
        }
    }

    /// Packetize one AV1 temporal unit (low-overhead OBUs) at `timestamp`.
    pub fn packetize(&mut self, temporal_unit: &[u8], timestamp: u32) -> Vec<Vec<u8>> {
        // Re-frame each OBU (minus the temporal delimiter) as a length-delimited
        // OBU element with obu_has_size_field cleared.
        let mut stream = Vec::with_capacity(temporal_unit.len());
        let mut new_cvs = false;
        for obu in crate::codec::obu::iter_obus(temporal_unit) {
            if obu.obu_type == AV1_OBU_TEMPORAL_DELIMITER {
                continue;
            }
            if obu.obu_type == AV1_OBU_SEQUENCE_HEADER {
                new_cvs = true;
            }
            let header_len = 1 + obu.has_extension as usize;
            let mut element = Vec::with_capacity(header_len + obu.payload.len());
            element.push(obu.raw[0] & !0x02); // clear obu_has_size_field
            if obu.has_extension {
                element.push(obu.raw[1]);
            }
            element.extend_from_slice(obu.payload);
            leb128_encode(element.len() as u64, &mut stream);
            stream.extend_from_slice(&element);
        }

        let mut packets = Vec::new();
        let chunks: Vec<&[u8]> = if stream.is_empty() {
            vec![&[]]
        } else {
            stream.chunks(self.max_payload).collect()
        };
        let n = chunks.len();
        for (i, chunk) in chunks.into_iter().enumerate() {
            let last = i + 1 == n;
            let mut pkt = Vec::with_capacity(12 + 1 + chunk.len());
            write_rtp_header(
                &mut pkt,
                self.payload_type,
                last,
                self.sequence,
                timestamp,
                self.ssrc,
            );
            self.sequence = self.sequence.wrapping_add(1);

            // Aggregation header: Z (continues previous packet) | Y (continues in
            // next) | W=0 (length-delimited elements) | N (new coded video seq).
            let mut agg = 0u8;
            if i > 0 {
                agg |= 0x80; // Z
            }
            if !last {
                agg |= 0x40; // Y
            }
            if i == 0 && new_cvs {
                agg |= 0x08; // N
            }
            pkt.push(agg);
            pkt.extend_from_slice(chunk);
            packets.push(pkt);
        }
        packets
    }
}

/// Reassembles AV1 RTP payloads into temporal units. Counterpart to
/// [`Av1Packetizer`]: it concatenates each packet's OBU-element bytes (past the
/// aggregation header) and, on the RTP marker, parses the length-delimited
/// elements back into low-overhead OBUs (re-adding each `obu_has_size_field`).
#[cfg(feature = "codec-av1")]
#[derive(Debug, Default)]
pub struct Av1Depacketizer {
    stream: Vec<u8>,
    new_cvs: bool,
    current_ts: Option<u32>,
}

#[cfg(feature = "codec-av1")]
impl Av1Depacketizer {
    /// A fresh depacketizer with no in-progress temporal unit.
    pub fn new() -> Self {
        Self::default()
    }

    /// Push one AV1 RTP payload. Returns a completed temporal unit when the RTP
    /// marker closes it.
    pub fn push(
        &mut self,
        payload: &[u8],
        marker: bool,
        timestamp: u32,
    ) -> Result<Option<AccessUnit>, DepacketizeError> {
        if payload.is_empty() {
            return Err(DepacketizeError::Truncated);
        }
        let agg = payload[0];
        if agg & 0x08 != 0 {
            self.new_cvs = true; // N: new coded video sequence
        }
        if self.current_ts.is_none() {
            self.current_ts = Some(timestamp);
        }
        self.stream.extend_from_slice(&payload[1..]);

        if !marker {
            return Ok(None);
        }

        // Marker: rebuild the temporal unit from length-delimited OBU elements.
        let stream = std::mem::take(&mut self.stream);
        let mut tu = Vec::with_capacity(stream.len() + 8);
        let mut pos = 0;
        while pos < stream.len() {
            let len = leb128_decode(&stream, &mut pos).ok_or(DepacketizeError::Truncated)?;
            let end = pos.checked_add(len).ok_or(DepacketizeError::Truncated)?;
            let element = stream.get(pos..end).ok_or(DepacketizeError::Truncated)?;
            pos = end;
            // Element → low-overhead OBU: set obu_has_size_field, insert the size.
            let hdr0 = *element.first().ok_or(DepacketizeError::Truncated)?;
            let has_ext = (hdr0 >> 2) & 1 == 1;
            let header_len = 1 + has_ext as usize;
            let obu_payload = element
                .get(header_len..)
                .ok_or(DepacketizeError::Truncated)?;
            tu.push(hdr0 | 0x02);
            if has_ext {
                tu.push(element[1]);
            }
            leb128_encode(obu_payload.len() as u64, &mut tu);
            tu.extend_from_slice(obu_payload);
        }

        let keyframe = std::mem::take(&mut self.new_cvs);
        let ts = self.current_ts.take().unwrap_or(timestamp);
        Ok(Some(AccessUnit {
            data: Bytes::from(tu),
            timestamp: ts,
            keyframe,
        }))
    }
}

/// Decode an unsigned LEB128 integer at `*pos` (advancing it), returning `None`
/// on truncation or overflow. Mirrors the codec-side decoder for RTP carriage.
#[cfg(feature = "codec-av1")]
fn leb128_decode(data: &[u8], pos: &mut usize) -> Option<usize> {
    let mut value: u64 = 0;
    for i in 0..8 {
        let byte = *data.get(*pos)?;
        *pos += 1;
        value |= ((byte & 0x7F) as u64) << (i * 7);
        if byte & 0x80 == 0 {
            return usize::try_from(value).ok();
        }
    }
    None
}

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

    /// Build a minimal 12-byte RTP packet with the given fields and payload.
    fn rtp(seq: u16, ts: u32, marker: bool, payload: &[u8]) -> Vec<u8> {
        let mut p = vec![0x80, if marker { 0x80 | 96 } else { 96 }];
        p.extend_from_slice(&seq.to_be_bytes());
        p.extend_from_slice(&ts.to_be_bytes());
        p.extend_from_slice(&[0, 0, 0, 1]); // ssrc
        p.extend_from_slice(payload);
        p
    }

    #[test]
    fn parses_fixed_header_and_payload_offset() {
        let pkt = rtp(7, 9000, true, &[0x65, 0xAA]);
        let h = RtpHeader::parse(&pkt).unwrap();
        assert_eq!(h.sequence, 7);
        assert_eq!(h.timestamp, 9000);
        assert!(h.marker);
        assert_eq!(h.payload_type, 96);
        assert_eq!(h.payload_offset, 12);
        assert_eq!(&pkt[h.payload_offset..], &[0x65, 0xAA]);
    }

    #[test]
    fn rejects_wrong_version_and_short_buffers() {
        assert!(RtpHeader::parse(&[0x00; 12]).is_none()); // version 0
        assert!(RtpHeader::parse(&[0x80; 4]).is_none()); // too short
    }

    #[test]
    fn honors_csrc_count_in_payload_offset() {
        let mut pkt = rtp(1, 0, false, &[0x41]);
        pkt[0] = 0x82; // version 2, CSRC count = 2
        let mut with_csrc = pkt[..12].to_vec();
        with_csrc.extend_from_slice(&[0xDE, 0xAD, 0xBE, 0xEF, 0, 0, 0, 0]); // 2 CSRCs
        with_csrc.push(0x41);
        let h = RtpHeader::parse(&with_csrc).unwrap();
        assert_eq!(h.payload_offset, 20);
    }

    #[test]
    fn aac_hbr_splits_two_access_units() {
        // AU-headers-length = 32 bits → two 16-bit AU-headers.
        // AU sizes 3 and 2 (top 13 bits of each 2-byte header).
        let mut p = Vec::new();
        p.extend_from_slice(&32u16.to_be_bytes()); // header bits
        p.extend_from_slice(&((3u16) << 3).to_be_bytes()); // AU-header: size 3
        p.extend_from_slice(&((2u16) << 3).to_be_bytes()); // AU-header: size 2
        p.extend_from_slice(&[0xA1, 0xA2, 0xA3]); // AU 1
        p.extend_from_slice(&[0xB1, 0xB2]); // AU 2
        let aus = AacDepacketizer::new().push(&p).unwrap();
        assert_eq!(aus.len(), 2);
        assert_eq!(&aus[0][..], &[0xA1, 0xA2, 0xA3]);
        assert_eq!(&aus[1][..], &[0xB1, 0xB2]);
    }

    #[test]
    fn aac_hbr_single_au() {
        let mut p = Vec::new();
        p.extend_from_slice(&16u16.to_be_bytes()); // one 16-bit AU-header
        p.extend_from_slice(&((4u16) << 3).to_be_bytes()); // size 4
        p.extend_from_slice(&[1, 2, 3, 4]);
        let aus = AacDepacketizer::new().push(&p).unwrap();
        assert_eq!(aus.len(), 1);
        assert_eq!(&aus[0][..], &[1, 2, 3, 4]);
    }

    #[test]
    fn aac_truncated_payload_errors() {
        assert_eq!(
            AacDepacketizer::new().push(&[0x00]),
            Err(DepacketizeError::Truncated)
        );
        // Declares one AU of size 8 but supplies only 2 data bytes.
        let mut p = 16u16.to_be_bytes().to_vec();
        p.extend_from_slice(&((8u16) << 3).to_be_bytes());
        p.extend_from_slice(&[1, 2]);
        assert_eq!(
            AacDepacketizer::new().push(&p),
            Err(DepacketizeError::Truncated)
        );
    }

    #[test]
    fn single_nal_packet_emits_annexb_on_marker() {
        let mut d = H264Depacketizer::new();
        // Type 1 (non-IDR slice), marker set → one access unit.
        let out = d.push(&[0x41, 0x9A, 0xBC], true, 3000, 1).unwrap().unwrap();
        assert_eq!(&out.data[..], &[0, 0, 0, 1, 0x41, 0x9A, 0xBC]);
        assert!(!out.keyframe);
        assert_eq!(out.timestamp, 3000);
    }

    #[test]
    fn idr_single_nal_is_flagged_keyframe() {
        let mut d = H264Depacketizer::new();
        let out = d.push(&[0x65, 0x01], true, 0, 1).unwrap().unwrap();
        assert!(out.keyframe);
    }

    #[test]
    fn packetizer_single_nal_round_trips_through_depacketizer() {
        // A small AU (two NALs) → single-NAL packets → reassembled identically.
        let au = [0, 0, 0, 1, 0x67, 0x42, 0x00, 0, 0, 0, 1, 0x65, 0x88, 0x99];
        let mut pkt = RtpPacketizer::new(96, 0xABCD, 1200);
        let packets = pkt.packetize(&au, 3000);
        assert_eq!(packets.len(), 2, "one packet per NAL");

        let mut depack = H264Depacketizer::new();
        let mut out = None;
        for p in &packets {
            let h = RtpHeader::parse(p).unwrap();
            if let Some(au) = depack
                .push(&p[h.payload_offset..], h.marker, h.timestamp, h.sequence)
                .unwrap()
            {
                out = Some(au);
            }
        }
        let out = out.expect("AU completed on the marker packet");
        assert_eq!(&out.data[..], &au);
        assert!(out.keyframe);
        assert_eq!(out.timestamp, 3000);
    }

    #[test]
    fn packetizer_fragments_oversized_nal_and_round_trips() {
        // One NAL larger than the MTU → FU-A fragments → reassembled identically.
        let mut nal = vec![0, 0, 0, 1, 0x65]; // start code + IDR NAL header
        nal.extend((0..600u16).map(|i| i as u8)); // long payload
        let mut pkt = RtpPacketizer::new(96, 1, 100); // tiny MTU forces FU-A
        let packets = pkt.packetize(&nal, 90);
        assert!(packets.len() > 1, "oversized NAL is fragmented");
        // Only the last packet carries the marker bit.
        let markers: Vec<bool> = packets
            .iter()
            .map(|p| RtpHeader::parse(p).unwrap().marker)
            .collect();
        assert_eq!(markers.iter().filter(|m| **m).count(), 1);
        assert!(markers.last().unwrap());

        let mut depack = H264Depacketizer::new();
        let mut out = None;
        for p in &packets {
            let h = RtpHeader::parse(p).unwrap();
            if let Some(au) = depack
                .push(&p[h.payload_offset..], h.marker, h.timestamp, h.sequence)
                .unwrap()
            {
                out = Some(au);
            }
        }
        assert_eq!(&out.unwrap().data[..], &nal[..]);
    }

    #[test]
    fn stap_a_splits_aggregated_nals() {
        // STAP-A (24): [24][size=2][AA BB][size=3][CC DD EE]
        let payload = [24, 0, 2, 0xAA, 0xBB, 0, 3, 0xCC, 0xDD, 0xEE];
        let mut d = H264Depacketizer::new();
        let out = d.push(&payload, true, 0, 1).unwrap().unwrap();
        assert_eq!(
            &out.data[..],
            &[0, 0, 0, 1, 0xAA, 0xBB, 0, 0, 0, 1, 0xCC, 0xDD, 0xEE]
        );
    }

    #[test]
    fn fu_a_reassembles_fragmented_nal() {
        let mut d = H264Depacketizer::new();
        // FU indicator 0x7C (F=0,NRI=3,type=28), FU header start 0x85 (S=1,type=5).
        assert!(d
            .push(&[0x7C, 0x85, 0x11, 0x22], false, 0, 1)
            .unwrap()
            .is_none());
        // Middle fragment (S=0,E=0).
        assert!(d.push(&[0x7C, 0x05, 0x33], false, 0, 2).unwrap().is_none());
        // End fragment (E=1), marker closes the AU.
        let out = d.push(&[0x7C, 0x45, 0x44], true, 0, 3).unwrap().unwrap();
        // Reconstructed NAL header: NRI 0x60 | type 5 = 0x65, then payload bytes.
        assert_eq!(&out.data[..], &[0, 0, 0, 1, 0x65, 0x11, 0x22, 0x33, 0x44]);
        assert!(out.keyframe);
    }

    #[test]
    fn fu_a_sequence_gap_reports_out_of_order() {
        let mut d = H264Depacketizer::new();
        d.push(&[0x7C, 0x85, 0x11], false, 0, 1).unwrap();
        // Jump from seq 1 to seq 5 mid-fragment.
        assert_eq!(
            d.push(&[0x7C, 0x05, 0x22], false, 0, 5),
            Err(DepacketizeError::OutOfOrder)
        );
    }

    #[test]
    fn timestamp_change_flushes_previous_au_without_marker() {
        let mut d = H264Depacketizer::new();
        // First AU, no marker.
        assert!(d.push(&[0x41, 0x01], false, 1000, 1).unwrap().is_none());
        // New timestamp flushes the first AU.
        let out = d.push(&[0x41, 0x02], false, 2000, 2).unwrap().unwrap();
        assert_eq!(out.timestamp, 1000);
        assert_eq!(&out.data[..], &[0, 0, 0, 1, 0x41, 0x01]);
    }

    // ── H.265 (RFC 7798) ────────────────────────────────────────────────────
    // H.265 NAL headers are two bytes; type = (byte0 >> 1) & 0x3F. Examples used
    // below: VPS=32 (0x40,0x01), IDR_W_RADL=19 (0x26,0x01).

    #[test]
    fn h265_single_nal_round_trips_through_depacketizer() {
        // VPS (non-VCL) + IDR (VCL keyframe), each a single-NAL packet.
        let au = [
            0, 0, 0, 1, 0x40, 0x01, 0xAA, // VPS (type 32)
            0, 0, 0, 1, 0x26, 0x01, 0x88, 0x99, // IDR (type 19)
        ];
        let mut pkt = RtpPacketizer::new_h265(96, 0xABCD, 1200);
        let packets = pkt.packetize(&au, 3000);
        assert_eq!(packets.len(), 2, "one packet per NAL");

        let mut depack = H265Depacketizer::new();
        let mut out = None;
        for p in &packets {
            let h = RtpHeader::parse(p).unwrap();
            if let Some(au) = depack
                .push(&p[h.payload_offset..], h.marker, h.timestamp, h.sequence)
                .unwrap()
            {
                out = Some(au);
            }
        }
        let out = out.expect("AU completed on the marker packet");
        assert_eq!(&out.data[..], &au);
        assert!(out.keyframe, "IRAP type 19 is a keyframe");
        assert_eq!(out.timestamp, 3000);
    }

    #[test]
    fn h265_fragments_oversized_nal_and_round_trips() {
        // One IDR NAL larger than the MTU → FU fragments → reassembled identically.
        let mut nal = vec![0, 0, 0, 1, 0x26, 0x01]; // start code + 2-byte IDR header
        nal.extend((0..600u16).map(|i| i as u8));
        let mut pkt = RtpPacketizer::new_h265(96, 1, 100); // tiny MTU forces FU
        let packets = pkt.packetize(&nal, 90);
        assert!(packets.len() > 1, "oversized NAL is fragmented");
        // Exactly one marker, on the last fragment.
        let markers: Vec<bool> = packets
            .iter()
            .map(|p| RtpHeader::parse(p).unwrap().marker)
            .collect();
        assert_eq!(markers.iter().filter(|m| **m).count(), 1);
        assert!(markers.last().unwrap());
        // Each FU packet carries a type-49 PayloadHdr.
        for p in &packets {
            let h = RtpHeader::parse(p).unwrap();
            let pt = (p[h.payload_offset] >> 1) & 0x3F;
            assert_eq!(pt, 49, "FU payload type");
        }

        let mut depack = H265Depacketizer::new();
        let mut out = None;
        for p in &packets {
            let h = RtpHeader::parse(p).unwrap();
            if let Some(au) = depack
                .push(&p[h.payload_offset..], h.marker, h.timestamp, h.sequence)
                .unwrap()
            {
                out = Some(au);
            }
        }
        assert_eq!(&out.unwrap().data[..], &nal[..]);
    }

    #[test]
    fn h265_ap_splits_aggregated_nals() {
        // AP (type 48): [0x60,0x01][size=2][AA BB][size=3][CC DD EE]
        let payload = [0x60, 0x01, 0, 2, 0xAA, 0xBB, 0, 3, 0xCC, 0xDD, 0xEE];
        let mut d = H265Depacketizer::new();
        let out = d.push(&payload, true, 0, 1).unwrap().unwrap();
        assert_eq!(
            &out.data[..],
            &[0, 0, 0, 1, 0xAA, 0xBB, 0, 0, 0, 1, 0xCC, 0xDD, 0xEE]
        );
    }

    #[test]
    fn h265_rejects_truncated_and_unsupported() {
        let mut d = H265Depacketizer::new();
        // One byte cannot hold a 2-byte NAL header.
        assert_eq!(
            d.push(&[0x26], true, 0, 1),
            Err(DepacketizeError::Truncated)
        );
        // PACI (type 50) is not supported.
        assert_eq!(
            d.push(&[50 << 1, 0x01, 0x00], true, 0, 2),
            Err(DepacketizeError::Unsupported(50))
        );
    }

    // ── VP9 ───────────────────────────────────────────────────────────────────

    fn vp9_depacketize(packets: &[Vec<u8>]) -> Option<AccessUnit> {
        let mut d = Vp9Depacketizer::new();
        let mut out = None;
        for p in packets {
            let h = RtpHeader::parse(p).unwrap();
            if let Some(f) = d
                .push(&p[h.payload_offset..], h.marker, h.timestamp)
                .unwrap()
            {
                out = Some(f);
            }
        }
        out
    }

    #[test]
    fn vp9_fragmented_frame_round_trips() {
        let frame: Vec<u8> = (0..500u16).map(|i| i as u8).collect();
        let mut pkt = Vp9Packetizer::new(98, 0x1234, 100); // small MTU → fragments
        let packets = pkt.packetize(&frame, 9000, true);
        assert!(packets.len() > 1, "frame fragmented");

        // Exactly one marker, on the last packet.
        let markers: Vec<bool> = packets
            .iter()
            .map(|p| RtpHeader::parse(p).unwrap().marker)
            .collect();
        assert_eq!(markers.iter().filter(|m| **m).count(), 1);
        assert!(markers.last().unwrap());

        let out = vp9_depacketize(&packets).expect("frame completed");
        assert_eq!(&out.data[..], &frame[..]);
        assert!(out.keyframe, "keyframe → P bit clear");
        assert_eq!(out.timestamp, 9000);
    }

    #[test]
    fn vp9_inter_frame_is_not_a_keyframe() {
        let mut pkt = Vp9Packetizer::new(98, 1, 1200);
        let packets = pkt.packetize(&[1, 2, 3], 0, false);
        assert_eq!(packets.len(), 1);
        let out = vp9_depacketize(&packets).expect("frame");
        assert_eq!(&out.data[..], &[1, 2, 3]);
        assert!(!out.keyframe, "P bit set → inter frame");
    }

    // ── AV1 ───────────────────────────────────────────────────────────────────

    #[cfg(feature = "codec-av1")]
    fn av1_depacketize(packets: &[Vec<u8>]) -> Option<AccessUnit> {
        let mut d = Av1Depacketizer::new();
        let mut out = None;
        for p in packets {
            let h = RtpHeader::parse(p).unwrap();
            if let Some(f) = d
                .push(&p[h.payload_offset..], h.marker, h.timestamp)
                .unwrap()
            {
                out = Some(f);
            }
        }
        out
    }

    #[cfg(feature = "codec-av1")]
    #[test]
    fn av1_temporal_unit_round_trips_without_delimiter() {
        // Low-overhead OBUs: temporal delimiter + sequence header + frame.
        let td = [0x12u8, 0x00];
        let seq = [0x0Au8, 0x02, 0xAA, 0xBB];
        let frame = [0x32u8, 0x03, 0x11, 0x22, 0x33];
        let mut tu = Vec::new();
        tu.extend_from_slice(&td);
        tu.extend_from_slice(&seq);
        tu.extend_from_slice(&frame);

        let mut pkt = Av1Packetizer::new(99, 7, 1200);
        let packets = pkt.packetize(&tu, 1000);
        let out = av1_depacketize(&packets).expect("TU completed");

        // The temporal delimiter is dropped; seq + frame survive, low-overhead.
        let mut expected = Vec::new();
        expected.extend_from_slice(&seq);
        expected.extend_from_slice(&frame);
        assert_eq!(&out.data[..], &expected[..]);
        assert!(out.keyframe, "sequence header → new coded video sequence");
        assert_eq!(out.timestamp, 1000);
    }

    #[cfg(feature = "codec-av1")]
    #[test]
    fn av1_large_temporal_unit_fragments_and_round_trips() {
        // A frame OBU with a 300-byte payload (size field leb128(300) = AC 02).
        let mut frame = vec![0x32u8, 0xAC, 0x02];
        frame.extend((0..300u16).map(|i| i as u8));
        let mut tu = vec![0x12u8, 0x00]; // temporal delimiter
        tu.extend_from_slice(&frame);

        let mut pkt = Av1Packetizer::new(99, 1, 64); // tiny MTU forces fragmentation
        let packets = pkt.packetize(&tu, 0);
        assert!(packets.len() > 1, "large TU fragmented");
        // Z set on every packet but the first; Y on every packet but the last.
        for (i, p) in packets.iter().enumerate() {
            let agg = p[RtpHeader::parse(p).unwrap().payload_offset];
            assert_eq!((agg & 0x80 != 0), i > 0, "Z continuation bit");
            assert_eq!(
                (agg & 0x40 != 0),
                i + 1 < packets.len(),
                "Y continuation bit"
            );
        }

        let out = av1_depacketize(&packets).expect("TU completed");
        assert_eq!(&out.data[..], &frame[..], "frame OBU reconstructed");
    }
}