str0m 0.18.0

WebRTC library in Sans-IO style
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
use super::{BitRead, CodecExtra, Depacketizer, PacketError, Packetizer, encode_leb_u63};

const OBU_EXTENSION_PRESENT_MASK: u8 = 0b0000_0100;
const OBU_SIZE_PRESENT_MASK: u8 = 0b0000_0010;
const OBU_TYPE_MASK: u8 = 0b0111_1000;
const AGGREGATION_HEADER_SIZE: usize = 1;
const MAX_NUM_OBUS_TO_OMTI_SIZE: usize = 3;

/// Detect whether an AV1 RTP payload contains a keyframe.
///
/// Checks the N bit (new coded video sequence) in the AV1 aggregation header.
/// N=1 indicates the first packet of a keyframe (random access point).
///
/// AV1 aggregation header layout: `Z|Y|W W|N|reserved`
/// - N (bit 3): 1 = new coded video sequence starts
pub fn detect_av1_keyframe(payload: &[u8]) -> bool {
    if payload.is_empty() {
        return false;
    }
    // N bit is bit 3 of the aggregation header
    payload[0] & 0x08 != 0
}

/// AV1 information describing the depacketized / packetized data
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct Av1CodecExtra {
    /// Flag which indicates that within [`MediaData`], there is an individual frame
    /// containing complete and independent visual information. This frame serves
    /// as a reference point for other frames in the video sequence.
    ///
    /// [`MediaData`]: crate::media::MediaData
    pub is_keyframe: bool,
}

/// AV1 packetizer
#[derive(Default, Debug)]
pub struct Av1Packetizer {
    packets: Vec<Packet>,
    obus: Vec<Obu>,
}

impl Av1Packetizer {
    fn emit(&mut self, mtu: usize, payloads: &mut Vec<Vec<u8>>) {
        if self.obus.is_empty() {
            return;
        }

        // Clear previous frame data
        self.packets.clear();

        // Reserve 1 byte for aggregation header
        let max_payload_size = mtu - AGGREGATION_HEADER_SIZE;
        let mut remaining_packet_size = max_payload_size;

        // Push as many obus as possible into each packet
        let mut current_packet = Packet::new(0);
        for (obu_idx, obu) in self.obus.iter().enumerate() {
            let mut previous_obu_extra_size = self.extra_size_for_previous_obu(&current_packet);
            let min_required_size = if current_packet.num_obu_elements >= MAX_NUM_OBUS_TO_OMTI_SIZE
            {
                2
            } else {
                1
            };

            // Check if new packet is needed
            if remaining_packet_size < previous_obu_extra_size + min_required_size {
                self.packets.push(current_packet);
                current_packet = Packet::new(obu_idx);
                remaining_packet_size = max_payload_size;
                previous_obu_extra_size = 0;
            }

            current_packet.packet_size += previous_obu_extra_size;
            current_packet.num_obu_elements += 1;
            remaining_packet_size -= previous_obu_extra_size;

            let must_write_obu_element_size =
                current_packet.num_obu_elements > MAX_NUM_OBUS_TO_OMTI_SIZE;
            let mut required_bytes = obu.size;
            if must_write_obu_element_size {
                required_bytes += leb_128_size(obu.size);
            }

            if required_bytes <= remaining_packet_size {
                current_packet.last_obu_size = obu.size;
                current_packet.packet_size += required_bytes;
                remaining_packet_size -= required_bytes;
                continue;
            }

            // Fragment the obu
            let max_first_fragment_size = match must_write_obu_element_size {
                true => self.max_fragment_size(remaining_packet_size),
                false => remaining_packet_size,
            };

            if max_first_fragment_size == 0 {
                current_packet.num_obu_elements -= 1;
                current_packet.packet_size -= previous_obu_extra_size;
            } else {
                current_packet.packet_size += max_first_fragment_size;
                if must_write_obu_element_size {
                    current_packet.packet_size += leb_128_size(max_first_fragment_size);
                }
                current_packet.last_obu_size = max_first_fragment_size;
            }

            // Middle fragments
            let mut obu_offset = max_first_fragment_size;
            while obu_offset + max_payload_size < obu.size {
                self.packets.push(current_packet);
                current_packet = Packet::new(obu_idx);
                current_packet.num_obu_elements = 1;
                current_packet.first_obu_offset = obu_offset;
                current_packet.last_obu_size = max_payload_size;
                current_packet.packet_size = max_payload_size;

                obu_offset += max_payload_size
            }

            // Last fragment
            let last_fragment_size = obu.size - obu_offset;
            self.packets.push(current_packet);
            current_packet = Packet::new(obu_idx);
            current_packet.num_obu_elements = 1;
            current_packet.first_obu_offset = obu_offset;
            current_packet.last_obu_size = last_fragment_size;
            current_packet.packet_size = last_fragment_size;

            remaining_packet_size = max_payload_size - last_fragment_size;
        }

        self.packets.push(current_packet);
        self.write_rtp_payloads(payloads)
    }

    fn write_rtp_payloads(&self, payloads: &mut Vec<Vec<u8>>) {
        for (i, packet) in self.packets.iter().enumerate() {
            let is_first_packet = i == 0;
            let mut rtp_payload: Vec<u8> = vec![0u8; AGGREGATION_HEADER_SIZE + packet.packet_size];
            let mut pos = 0;

            let header = self.aggregation_header(packet, &self.obus, is_first_packet);
            rtp_payload[pos] = header;
            pos += 1;

            let mut obu_offset = packet.first_obu_offset;
            // Write all obu elements except the last one
            for obu_idx in 0..(packet.num_obu_elements - 1) {
                let obu = &self.obus[packet.first_obu + obu_idx];
                let obu_fragment_size = obu.size - obu_offset;
                pos += encode_leb_u63(obu_fragment_size as u64, &mut rtp_payload[pos..]);

                if obu_offset == 0 {
                    rtp_payload[pos] = obu.header & !OBU_SIZE_PRESENT_MASK;
                    pos += 1;
                }

                if obu_offset <= 1 && obu.has_extension() {
                    rtp_payload[pos] = obu.ext_header;
                    pos += 1;
                }

                let payload_offset =
                    obu_offset.saturating_sub(if obu.has_extension() { 2 } else { 1 });
                let payload_size = obu.payload.len() - payload_offset;

                if !obu.payload.is_empty() && payload_size > 0 {
                    rtp_payload[pos..pos + payload_size].copy_from_slice(
                        &obu.payload[payload_offset..payload_offset + payload_size],
                    );
                }

                pos += payload_size;
                obu_offset = 0;
            }

            let last_obu = &self.obus[packet.first_obu + packet.num_obu_elements - 1];
            let mut obu_fragment_size = packet.last_obu_size;
            if packet.num_obu_elements > MAX_NUM_OBUS_TO_OMTI_SIZE {
                pos += encode_leb_u63(obu_fragment_size as u64, &mut rtp_payload[pos..]);
            }

            if obu_offset == 0 && obu_fragment_size > 0 {
                rtp_payload[pos] = last_obu.header & !OBU_SIZE_PRESENT_MASK;
                pos += 1;
                obu_fragment_size -= 1;
            }

            if obu_offset <= 1 && last_obu.has_extension() && obu_fragment_size > 0 {
                rtp_payload[pos] = last_obu.ext_header;
                pos += 1;
                obu_fragment_size -= 1;
            }

            let payload_offset =
                obu_offset.saturating_sub(if last_obu.has_extension() { 2 } else { 1 });
            rtp_payload[pos..pos + obu_fragment_size].copy_from_slice(
                &last_obu.payload[payload_offset..payload_offset + obu_fragment_size],
            );

            payloads.push(rtp_payload);
        }
    }

    fn aggregation_header(&self, packet: &Packet, obus: &[Obu], is_first_packet: bool) -> u8 {
        let mut agg_header = 0;

        // set Z flag: the first obu element is the continuation of the previous one
        if packet.first_obu_offset > 0 {
            agg_header |= 1 << 7;
        }

        // set Y flag: the last obu element is continued in the next packet
        let last_obu_offset = if packet.num_obu_elements == 1 {
            packet.first_obu_offset
        } else {
            0
        };
        let last_obu_is_fragment = (last_obu_offset + packet.last_obu_size)
            < obus[packet.first_obu + packet.num_obu_elements - 1].size;
        if last_obu_is_fragment {
            agg_header |= 1 << 6;
        }

        // set W field: small number of obu elements in the packet
        if packet.num_obu_elements <= MAX_NUM_OBUS_TO_OMTI_SIZE {
            agg_header |= packet.num_obu_elements << 4;
        }

        // set N flag:
        if let Some(ObuType::SequenceHeader) = obus[0].obu_type() {
            if is_first_packet {
                agg_header |= 1 << 3;
            }
        }

        agg_header as u8
    }

    /// Adding new OBU to the last packet would mean that the previous one is
    /// no longer the final OBU element in that packet. Any OBU that is not the
    /// last element must be prefixed with its length. `extra_size_for_previous_obu`
    /// computes the number of bytes required to encode that length.
    fn extra_size_for_previous_obu(&self, packet: &Packet) -> usize {
        if packet.packet_size == 0 {
            return 0;
        }

        if packet.num_obu_elements > MAX_NUM_OBUS_TO_OMTI_SIZE {
            return 0;
        }

        leb_128_size(packet.last_obu_size)
    }

    // Given the number of free bytes remaining in a packet, the function returns the largest
    // OBU fragment size that will fit into the packet
    // That is, FragmentSize + Leb128Size(FragmentSize) must not exceed remaining_bytes
    fn max_fragment_size(&self, size: usize) -> usize {
        if size <= 1 {
            return 0;
        }

        let mut idx = 1;
        loop {
            if size < (1 << 7 * idx) + 1 {
                return size - idx;
            }
            idx += 1;
        }
    }
}

impl Packetizer for Av1Packetizer {
    fn packetize(&mut self, mtu: usize, payload: &[u8]) -> Result<Vec<Vec<u8>>, PacketError> {
        if payload.is_empty() || mtu <= AGGREGATION_HEADER_SIZE {
            return Ok(vec![]);
        }

        let mut payloads = vec![];
        parse_obus(payload, &mut self.obus)?;
        self.emit(mtu, &mut payloads);

        Ok(payloads)
    }

    fn is_marker(&mut self, _data: &[u8], _previous: Option<&[u8]>, last: bool) -> bool {
        last
    }
}

/// AV1 Depacketizer
#[derive(Default, Debug)]
pub struct Av1Depacketizer {
    /// current obu payload
    obu_buffer: Vec<u8>,

    /// reusable buffer for parsed OBUs
    parsed_obus: Vec<Obu>,

    /// length of current obu
    obu_length: usize,

    /// aggregation header Z bit
    z: bool,

    /// aggregation header Y bit
    y: bool,

    /// aggregation header N bit
    n: bool,

    /// Number of obus in packet
    obu_count: u8,
}

impl Av1Depacketizer {
    fn parse_aggregation_header(&mut self, agg_header: u8) {
        // TODO: store these values as mask
        self.z = agg_header & (1 << 7) != 0;
        self.y = agg_header & (1 << 6) != 0;
        self.obu_count = (agg_header & 0b0011_0000) >> 4;
        self.n = agg_header & (1 << 3) != 0;
    }
}

impl Depacketizer for Av1Depacketizer {
    fn out_size_hint(&self, packets_size: usize) -> Option<usize> {
        Some(packets_size)
    }

    fn depacketize(
        &mut self,
        packet: &[u8],
        out: &mut Vec<u8>,
        codec_extra: &mut super::CodecExtra,
    ) -> Result<(), PacketError> {
        if packet.is_empty() {
            return Err(PacketError::ErrShortPacket);
        }

        let mut reader = (packet, 0);

        self.parse_aggregation_header(packet[0]);
        reader.skip_bytes(1);

        // if packet does not start with a continuation of an obu fragment
        // from the previous packet new obu starts
        if !self.z {
            self.obu_length = 0;
            self.obu_buffer.clear();
        }

        // set the key frame flag if N bit is set and clear the obu buffer
        // as it cannot start with a fragment of the previous packet
        let mut is_keyframe = matches!(
            *codec_extra,
            CodecExtra::Av1(Av1CodecExtra { is_keyframe: true })
        );
        if self.n {
            is_keyframe = true;
            self.obu_length = 0;
            self.obu_buffer.clear();
        }
        *codec_extra = CodecExtra::Av1(Av1CodecExtra { is_keyframe });

        let mut obu_idx = 0;
        while reader.remaining_bits() > 0 {
            let is_first_obu = obu_idx == 0;
            let mut is_last_obu = self.obu_count != 0 && obu_idx == (self.obu_count - 1);

            // Read the length of obu
            let fragment_obu_length = if self.obu_count == 0 || !is_last_obu {
                let len = reader
                    .get_leb128()
                    .ok_or(PacketError::ErrAv1CorruptedPacket)?;

                if self.obu_count == 0 && len == reader.remaining_bytes() {
                    is_last_obu = true;
                }

                len
            } else {
                reader.remaining_bytes()
            };

            // Safety checks
            if fragment_obu_length == 0 {
                return Err(PacketError::ErrAv1CorruptedPacket);
            }
            if reader.byte_offset() > packet.len()
                || fragment_obu_length > packet.len() - reader.byte_offset()
            {
                return Err(PacketError::ErrAv1CorruptedPacket);
            }

            if is_first_obu && self.z {
                // the previous fragment is lost, drop the buffer
                if self.obu_buffer.is_empty() {
                    reader.skip_bytes(fragment_obu_length);
                    obu_idx = 1;
                    continue;
                }
            }

            let offset = reader.byte_offset();
            self.obu_buffer
                .extend_from_slice(&packet[offset..offset + fragment_obu_length]);
            reader.skip_bytes(fragment_obu_length);

            if is_last_obu && self.y {
                self.obu_length += fragment_obu_length;
                break;
            }

            self.obu_length += fragment_obu_length;

            parse_obus(&self.obu_buffer, &mut self.parsed_obus)?;
            let Some(obu) = self.parsed_obus.first_mut() else {
                self.obu_length = 0;
                self.obu_buffer.clear();
                obu_idx += 1;
                continue;
            };

            // Write the obu payload to output
            // set size flag
            let size_flag_set = obu.header & OBU_SIZE_PRESENT_MASK != 0;
            obu.header |= OBU_SIZE_PRESENT_MASK;
            out.push(obu.header);
            self.obu_length = self.obu_length.saturating_sub(1);

            // add extension if any
            if obu.has_extension() {
                out.push(obu.ext_header);
                self.obu_length = self.obu_length.saturating_sub(1);
            }

            // add size if not present
            if !size_flag_set {
                let mut temp_space = [0u8; 9];
                let bytes_written = encode_leb_u63(self.obu_length as u64, &mut temp_space[..]);
                out.extend_from_slice(&temp_space[..bytes_written]);
            }

            // finally payload
            if self.obu_length > self.obu_buffer.len() {
                return Err(PacketError::ErrAv1CorruptedPacket);
            }
            let start_idx = self.obu_buffer.len() - self.obu_length;
            out.extend_from_slice(&self.obu_buffer[start_idx..start_idx + self.obu_length]);

            self.obu_length = 0;
            self.obu_buffer.clear();

            if is_last_obu {
                self.obu_length = 0;
                self.obu_buffer.clear();
                break;
            }

            obu_idx += 1;
        }

        Ok(())
    }

    fn is_partition_head(&self, packet: &[u8]) -> bool {
        if packet.is_empty() {
            return false;
        }

        // Z bit in the aggregation header is set to 0
        packet[0] & (1 << 7) == 0
    }

    fn is_partition_tail(&self, marker: bool, _payload: &[u8]) -> bool {
        marker
    }
}

#[repr(u8)]
enum ObuType {
    SequenceHeader = 1,
    TemporalDelimiter = 2,
    FrameHeader = 3,
    TileGroup = 4,
    MetaData = 5,
    Frame = 6,
    RedundantFrameHeader = 7,
    TileList = 8,
    Padding = 15,
}

impl ObuType {
    fn include_in_packetization(self) -> bool {
        !matches!(
            self,
            Self::TemporalDelimiter | Self::TileList | Self::Padding
        )
    }
}

/// Represents an OBU (Open Bitstream Unit) with its header, extension, payload, and size.
#[derive(Default, Debug)]
struct Obu {
    header: u8,
    ext_header: u8,
    payload: Vec<u8>,
    size: usize,
}

impl Obu {
    fn has_extension(&self) -> bool {
        (self.header & OBU_EXTENSION_PRESENT_MASK) != 0
    }

    fn has_size(&self) -> bool {
        (self.header & OBU_SIZE_PRESENT_MASK) != 0
    }

    fn obu_type(&self) -> Option<ObuType> {
        match (self.header & OBU_TYPE_MASK) >> 3 {
            1 => Some(ObuType::SequenceHeader),
            2 => Some(ObuType::TemporalDelimiter),
            3 => Some(ObuType::FrameHeader),
            4 => Some(ObuType::TileGroup),
            5 => Some(ObuType::MetaData),
            6 => Some(ObuType::Frame),
            7 => Some(ObuType::RedundantFrameHeader),
            8 => Some(ObuType::TileList),
            15 => Some(ObuType::Padding),
            _ => None,
        }
    }
}

/// The `Packet` struct holds information about the OBU (Open Bitstream Unit) and
/// related metadata necessary for constructing an RTP packet payload during packetization
#[derive(Debug)]
struct Packet {
    first_obu: usize,
    num_obu_elements: usize,
    first_obu_offset: usize,
    last_obu_size: usize,
    packet_size: usize,
}

impl Packet {
    pub fn new(first_obu: usize) -> Self {
        Packet {
            first_obu,
            num_obu_elements: 0,
            first_obu_offset: 0,
            last_obu_size: 0,
            packet_size: 0,
        }
    }
}

/// Returns the number of bytes required to encode a value using unsigned LEB128 encoding.
/// LEB128 uses variable-length encoding with 7 bits per byte, and this function computes
/// how many bytes are needed to represent the given `value`.
pub fn leb_128_size(mut value: usize) -> usize {
    let mut size = 0;

    while value >= 0x80 {
        size += 1;
        value >>= 7;
    }

    size + 1
}

/// OBU Header Structure (8 bits total):
///
///  0 1 2 3 4 5 6 7
/// +-+-+-+-+-+-+-+-+
/// |F|   T   |S|E|R|
/// +-+-+-+-+-+-+-+-+
///
/// Explanation of each bit:
/// - F (1 bit) - OBU Forbidden Bit: must be set to 0.
/// - T (4 bits) - OBU Type: This field specifies the type of data structure contained in the OBU payload.
/// - S (1 bit) - OBU Has Size Field: A flag indicating whether the obu_size syntax element will be present.
/// - E (1 bit) - OBU Extension Flag: A flag indicatin if the optional obu_extension_header is present.
/// - R (1 bit) - OBU Reserved Bits: must be set to 0. The value is ignored by a decoder.
fn parse_obus(payload: &[u8], parsed_obus: &mut Vec<Obu>) -> Result<(), PacketError> {
    let mut reader = (payload, 0);
    let mut obu_idx = 0;

    while reader.remaining_bits() > 0 {
        // Reuse existing Obu entry if available, otherwise grow the Vec
        if obu_idx >= parsed_obus.len() {
            parsed_obus.push(Obu::default());
        }
        let obu = &mut parsed_obus[obu_idx];

        obu.header = reader.get_u8().ok_or(PacketError::ErrAv1CorruptedPacket)?;
        obu.ext_header = 0;
        obu.size = 1;

        if obu.has_extension() {
            obu.ext_header = reader.get_u8().ok_or(PacketError::ErrAv1CorruptedPacket)?;
            obu.size += 1;
        }

        // Reuse the existing payload Vec — clear preserves capacity
        obu.payload.clear();

        if obu.has_size() {
            let obu_size = reader
                .get_leb128()
                .ok_or(PacketError::ErrAv1CorruptedPacket)?;
            if obu_size > reader.remaining_bytes() {
                return Err(PacketError::ErrAv1CorruptedPacket);
            }
            let bytes = reader
                .get_bytes(obu_size)
                .ok_or(PacketError::ErrAv1CorruptedPacket)?;
            obu.payload.extend_from_slice(bytes);
        } else {
            obu.payload.extend_from_slice(reader.get_remaining());
        }
        obu.size += obu.payload.len();

        if let Some(obu_type) = obu.obu_type() {
            if obu_type.include_in_packetization() {
                obu_idx += 1;
            }
        }
    }

    // Trim any leftover entries from previous calls
    parsed_obus.truncate(obu_idx);
    Ok(())
}

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

    /// AV1 Packetizer tets
    #[test]
    fn packetize_one_frame_type_obu_without_size() {
        let payload = &[0x30, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07];
        let mut packetizer = Av1Packetizer::default();

        let result = packetizer.packetize(1200, payload);

        assert!(result.is_ok());
        assert_eq!(
            result.unwrap(),
            [[0x10, 0x30, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07]]
        );
    }

    #[test]
    fn packetize_one_frame_type_obu_without_size_with_extension() {
        let payload = &[0x34, 0x28, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07];
        let mut packetizer = Av1Packetizer::default();

        let result = packetizer.packetize(1200, payload);

        assert!(result.is_ok());
        assert_eq!(
            result.unwrap(),
            [[0x10, 0x34, 0x28, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07]]
        );
    }

    #[test]
    fn packetize_one_frame_type_obu_remove_size_field_without_extension() {
        let payload = &[0x32, 0x07, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11];
        let mut packetizer = Av1Packetizer::default();

        let result = packetizer.packetize(1200, payload);

        assert!(result.is_ok());
        assert_eq!(
            result.unwrap(),
            [[0x10, 0x30, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11]]
        );
    }

    #[test]
    fn packetize_one_frame_type_obu_remove_size_field_with_extension() {
        let payload = &[0x36, 0x28, 0x07, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07];
        let mut packetizer = Av1Packetizer::default();

        let result = packetizer.packetize(1200, payload);

        assert!(result.is_ok());
        assert_eq!(
            result.unwrap(),
            [[0x10, 0x34, 0x28, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07]]
        );
    }

    #[test]
    fn omit_size_for_last_obu_when_three_obus_fits_into_the_packet() {
        let payload = &[
            0x0a, 0x06, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, // sequence header
            0x2a, 0x04, 0x0b, 0x0c, 0x0d, 0x0e, // metadata
            0x32, 0x06, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, // frame
        ];
        let mut packetizer = Av1Packetizer::default();

        let result = packetizer.packetize(1200, payload);

        assert!(result.is_ok());
        assert_eq!(
            result.unwrap(),
            [[
                0x38, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x05, 0x28, 0x0b, 0x0c, 0x0d,
                0x0e, 0x30, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a
            ]]
        );
    }

    #[test]
    fn use_size_for_all_obus_when_four_obus_fit_into_the_packet() {
        let payload = &[
            0x0a, 0x06, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, // sequence header
            0x2a, 0x04, 0x0b, 0x0c, 0x0d, 0x0e, // metadata
            0x1a, 0x03, 0x15, 0x16, 0x17, // frame
            0x22, 0x06, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, // tile group
        ];
        let mut packetizer = Av1Packetizer::default();

        let result = packetizer.packetize(1200, payload);

        assert!(result.is_ok());
        assert_eq!(
            result.unwrap(),
            [[
                0x08, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x05, 0x28, 0x0b, 0x0c, 0x0d,
                0x0e, 0x04, 0x18, 0x15, 0x16, 0x17, 0x07, 0x20, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24
            ]]
        );
    }

    #[test]
    fn discards_temporal_delimiter_and_tile_list_obu() {
        let payload = &[
            0x12, 0x00, // temporal delimeter
            0x2a, 0x00, // metadata
            0x42, 0x06, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, // tile list
            0x1a, 0x03, 0x15, 0x16, 0x17, // frame
            0x22, 0x06, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, // tile group
        ];
        let mut packetizer = Av1Packetizer::default();

        let result = packetizer.packetize(1200, payload);

        assert!(result.is_ok());
        assert_eq!(
            result.unwrap(),
            [[
                0x30, 0x01, 0x28, 0x04, 0x18, 0x15, 0x16, 0x17, 0x20, 0x1f, 0x20, 0x21, 0x22, 0x23,
                0x24
            ]]
        );
    }

    #[test]
    fn split_two_obus_into_two_packets_force_split_obu_header() {
        let payload = &[
            0x1e, 0x28, 0x01, 0x15, // frame
            0x26, 0x28, 0x04, 0x0b, 0x0c, 0x0d, 0x0e, // tile group
        ];
        let mut packetizer = Av1Packetizer::default();

        let result = packetizer.packetize(6, payload);

        assert!(result.is_ok());
        assert_eq!(
            result.unwrap(),
            vec![
                vec![0x60, 0x03, 0x1c, 0x28, 0x15, 0x24],
                vec![0x90, 0x28, 0x0b, 0x0c, 0x0d, 0x0e]
            ]
        );
    }

    #[test]
    fn set_nbit_at_the_first_packet_of_coded_video_sequence() {}

    #[test]
    fn split_single_obu_into_two_packets() {
        let payload = &[
            0x32, 0x09, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13,
        ];
        let mut packetizer = Av1Packetizer::default();

        let result = packetizer.packetize(8, payload);

        assert!(result.is_ok());
        assert_eq!(
            result.unwrap(),
            vec![
                vec![0x50, 0x30, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10],
                vec![0x90, 0x11, 0x12, 0x13]
            ]
        );
    }

    #[test]
    fn split_single_obu_into_many_packets() {
        let mut payload: Vec<u8> = vec![0x32, 0xB0, 0x09]; // obu header and leb128 encoded size
        payload.extend(vec![27u8; 1200]); // obu payload

        let mut packetizer = Av1Packetizer::default();

        let result = packetizer.packetize(100, &payload);

        assert!(result.is_ok());
        assert_eq!(result.unwrap().len(), 13 as usize);
    }

    #[test]
    fn split_two_obus_into_two_packets() {
        let payload = &[
            0x0a, 0x02, 0x0b, 0x0c, // sequence header
            0x32, 0x09, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, // frame
        ];
        let mut packetizer = Av1Packetizer::default();

        let result = packetizer.packetize(8, payload);

        assert!(result.is_ok());
        assert_eq!(
            result.unwrap(),
            vec![
                vec![0x68, 0x03, 0x08, 0x0b, 0x0c, 0x30, 0x01, 0x02],
                vec![0x90, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09]
            ]
        );
    }

    #[test]
    fn split_single_obu_into_two_packets_because_of_mtu_limit() {
        let payload = &[
            0x32, 0x09, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13,
        ];
        let mut packetizer = Av1Packetizer::default();

        let result = packetizer.packetize(10, payload);

        assert!(result.is_ok());
        assert_eq!(
            result.unwrap(),
            vec![
                vec![0x50, 0x30, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12],
                vec![0x90, 0x13]
            ]
        );
    }

    /// AV1 Depacketizer tests
    #[test]
    fn obu_payload_size_set_when_absent() {
        let paylod = &[0x10, 0x30, 0x14, 0x1e, 0x28];
        let mut out = Vec::new();
        let mut codec_extra = CodecExtra::None;
        let mut depacketizer = Av1Depacketizer::default();

        let result = depacketizer.depacketize(paylod, &mut out, &mut codec_extra);

        assert!(result.is_ok());
        assert_eq!(out, vec![0x32, 0x03, 0x14, 0x1e, 0x28]);
    }

    #[test]
    fn obu_payload_size_set_when_present() {
        let paylod = &[0x10, 0x32, 0x03, 0x14, 0x1e, 0x28];
        let mut out = Vec::new();
        let mut codec_extra = CodecExtra::None;
        let mut depacketizer = Av1Depacketizer::default();

        let result = depacketizer.depacketize(paylod, &mut out, &mut codec_extra);

        assert!(result.is_ok());
        assert_eq!(out, vec![0x32, 0x03, 0x14, 0x1e, 0x28]);
    }

    #[test]
    fn obu_payload_size_set_after_extension_when_absent() {
        let paylod = &[0x10, 0x34, 0x48, 0x14, 0x1e, 0x28];
        let mut out = Vec::new();
        let mut codec_extra = CodecExtra::None;
        let mut depacketizer = Av1Depacketizer::default();

        let result = depacketizer.depacketize(paylod, &mut out, &mut codec_extra);

        assert!(result.is_ok());
        assert_eq!(out, vec![0x36, 0x48, 0x03, 0x14, 0x1e, 0x28]);
    }

    #[test]
    fn obu_payload_size_set_after_extension_when_present() {
        let paylod = &[0x10, 0x36, 0x48, 0x03, 0x14, 0x1e, 0x28];
        let mut out = Vec::new();
        let mut codec_extra = CodecExtra::None;
        let mut depacketizer = Av1Depacketizer::default();

        let result = depacketizer.depacketize(paylod, &mut out, &mut codec_extra);

        assert!(result.is_ok());
        assert_eq!(out, vec![0x36, 0x48, 0x03, 0x14, 0x1e, 0x28]);
    }

    #[test]
    fn one_packet_with_two_obus() {
        let paylod = &[0x20, 0x02, 0x08, 0x0a, 0x30, 0x14];
        let mut out = Vec::new();
        let mut codec_extra = CodecExtra::None;
        let mut depacketizer = Av1Depacketizer::default();

        let result = depacketizer.depacketize(paylod, &mut out, &mut codec_extra);

        assert!(result.is_ok());
        assert_eq!(out, vec![0x0a, 0x01, 0x0a, 0x32, 0x01, 0x14]);
    }

    #[test]
    fn one_obu_from_two_packets() {
        let payload1 = &[0x50, 0x30, 0x14, 0x1e];
        let payload2 = &[0x90, 0x28];
        let mut out = Vec::new();
        let mut codec_extra = CodecExtra::None;
        let mut depacketizer = Av1Depacketizer::default();

        let result = depacketizer.depacketize(payload1, &mut out, &mut codec_extra);
        assert!(result.is_ok());

        let result = depacketizer.depacketize(payload2, &mut out, &mut codec_extra);
        assert!(result.is_ok());
        assert_eq!(out, vec![0x32, 0x03, 0x14, 0x1e, 0x28]);
    }

    #[test]
    fn two_packets_with_three_obus() {
        let payload1 = &[0x60, 0x02, 0x08, 0x0a, 0x30, 0x14, 0x1e];
        let payload2 = &[0x90, 0x28];
        let mut out = Vec::new();
        let mut codec_extra = CodecExtra::None;
        let mut depacketizer = Av1Depacketizer::default();

        let result = depacketizer.depacketize(payload1, &mut out, &mut codec_extra);
        assert!(result.is_ok());

        let result = depacketizer.depacketize(payload2, &mut out, &mut codec_extra);
        assert!(result.is_ok());
        assert_eq!(out, vec![0x0a, 0x01, 0x0a, 0x32, 0x03, 0x14, 0x1e, 0x28]);
    }

    #[test]
    fn two_packets_with_many_obus_some_with_extensions() {
        let payload1 = &[
            0x40, 0x02, 0x08, 0x0a, 0x02, 0x28, 0x14, 0x04, 0x2c, 0x30, 0x14, 0x1e, 0x05, 0x34,
            0x30, 0x28, 0x32, 0x3c,
        ];
        let payload2 = &[0x90, 0x46, 0x50, 0x5a];
        let mut out = Vec::new();
        let mut codec_extra = CodecExtra::None;
        let mut depacketizer = Av1Depacketizer::default();

        let result = depacketizer.depacketize(payload1, &mut out, &mut codec_extra);
        assert!(result.is_ok());

        let result = depacketizer.depacketize(payload2, &mut out, &mut codec_extra);
        assert!(result.is_ok());
        assert_eq!(
            out,
            vec![
                0x0a, 0x01, 0x0a, 0x2a, 0x01, 0x14, 0x2e, 0x30, 0x02, 0x14, 0x1e, 0x36, 0x30, 0x06,
                0x28, 0x32, 0x3c, 0x46, 0x50, 0x5a
            ]
        );
    }

    #[test]
    fn one_obu_from_many_packets() {
        let payload1 = &[0x50, 0x30, 0x0b, 0x0c];
        let payload2 = &[0xd0, 0x0d, 0x0e];
        let payload3 = &[0xd0, 0x0f, 0x10, 0x11];
        let payload4 = &[0x90, 0x12];
        let mut out = Vec::new();
        let mut codec_extra = CodecExtra::None;
        let mut depacketizer = Av1Depacketizer::default();

        let result = depacketizer.depacketize(payload1, &mut out, &mut codec_extra);
        assert!(result.is_ok());
        let result = depacketizer.depacketize(payload2, &mut out, &mut codec_extra);
        assert!(result.is_ok());
        let result = depacketizer.depacketize(payload3, &mut out, &mut codec_extra);
        assert!(result.is_ok());
        let result = depacketizer.depacketize(payload4, &mut out, &mut codec_extra);
        assert!(result.is_ok());
        assert_eq!(
            out,
            vec![0x32, 0x08, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12]
        );
    }

    #[test]
    fn many_packets_with_border_aligned_obus() {
        let payload1 = &[0x60, 0x03, 0x18, 0x0b, 0x0c, 0x20, 0x15, 0x16, 0x17];
        let payload2 = &[0x90, 0x18, 0x19, 0x1a, 0x1b];
        let payload3 = &[0x60, 0x03, 0x38, 0x0b, 0x0c, 0x20, 0x1f, 0x20];
        let payload4 = &[0x90, 0x21, 0x22, 0x23, 0x24];
        let mut out = Vec::new();
        let mut codec_extra = CodecExtra::None;
        let mut depacketizer = Av1Depacketizer::default();

        let result = depacketizer.depacketize(payload1, &mut out, &mut codec_extra);
        assert!(result.is_ok());
        let result = depacketizer.depacketize(payload2, &mut out, &mut codec_extra);
        assert!(result.is_ok());
        let result = depacketizer.depacketize(payload3, &mut out, &mut codec_extra);
        assert!(result.is_ok());
        let result = depacketizer.depacketize(payload4, &mut out, &mut codec_extra);
        assert!(result.is_ok());
        assert_eq!(
            out,
            vec![
                0x1a, 0x02, 0x0b, 0x0c, 0x22, 0x07, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x3a,
                0x02, 0x0b, 0x0c, 0x22, 0x06, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24
            ]
        );
    }

    #[test]
    fn one_packet_one_obu_with_payload_size_127_bytes() {
        let mut payload = [0; 131];
        let mut out = Vec::new();
        let mut codec_extra = CodecExtra::None;
        let mut depacketizer = Av1Depacketizer::default();

        payload[0] = 0b0000_0000; // aggregation header
        payload[1] = 0x80; // leb128 encoded size of 128 bytes
        payload[2] = 0x01; // in two bytes
        payload[3] = 0b0011_0000; // obu_header with size and extension bits unset.
        payload[4 + 42] = 0x42; // random

        let result = depacketizer.depacketize(&payload, &mut out, &mut codec_extra);
        assert!(result.is_ok());
        assert_eq!(out[0], 0b0011_0010); // size bit set
        assert_eq!(out[1], 127); // obu payloa size, 1 byte is enough
        assert_eq!(out[44], 0x42); // check random byte
    }

    #[test]
    fn two_packets_one_obu_with_payload_size_128_bytes() {
        let mut payload1 = [0; 35];
        let mut payload2 = [0; 98];
        let mut out = Vec::new();
        let mut codec_extra = CodecExtra::None;
        let mut depacketizer = Av1Depacketizer::default();

        payload1[0] = 0b0100_0000; // aggregation header
        payload1[1] = 33; // payload size
        payload1[2] = 0b0011_0000; // obu_header with size and extension bits unset.
        payload1[3 + 10] = 0x10; // random

        payload2[0] = 0b1000_0000;
        payload2[1] = 96;
        payload2[2 + 20] = 0x20;

        let result = depacketizer.depacketize(&payload1, &mut out, &mut codec_extra);
        assert!(result.is_ok());
        let result = depacketizer.depacketize(&payload2, &mut out, &mut codec_extra);
        assert!(result.is_ok());
        assert_eq!(out[0], 0b0011_0010);
        assert_eq!(out[1], 0x80);
        assert_eq!(out[2], 0x01);
        assert_eq!(out[3 + 10], 0x10);
        assert_eq!(out[3 + 32 + 20], 0x20);
    }

    // Regression tests for leb_128_size boundary values.
    // The bug was `value > 0x80` instead of `value >= 0x80`.
    // LEB128 encodes 7 bits per byte, so values >= 128 need 2 bytes,
    // values >= 16384 need 3 bytes, etc.

    #[test]
    fn leb128_size_boundary_at_128() {
        // 127 fits in 1 byte (7 bits), 128 needs 2 bytes
        assert_eq!(leb_128_size(0), 1);
        assert_eq!(leb_128_size(1), 1);
        assert_eq!(leb_128_size(127), 1);
        assert_eq!(leb_128_size(128), 2); // was incorrectly 1 before fix
        assert_eq!(leb_128_size(129), 2);
        assert_eq!(leb_128_size(255), 2);
    }

    #[test]
    fn leb128_size_boundary_at_16384() {
        // 16383 fits in 2 bytes (14 bits), 16384 needs 3 bytes
        assert_eq!(leb_128_size(16383), 2);
        assert_eq!(leb_128_size(16384), 3); // was incorrectly 2 before fix
        assert_eq!(leb_128_size(16385), 3);
    }

    #[test]
    fn leb128_size_boundary_at_2097152() {
        // 2097151 fits in 3 bytes (21 bits), 2097152 needs 4 bytes
        assert_eq!(leb_128_size(2097151), 3);
        assert_eq!(leb_128_size(2097152), 4); // was incorrectly 3 before fix
    }

    // Regression test: packetize an OBU with exactly 128 bytes of payload.
    // This triggers the leb_128_size boundary (128 needs 2-byte LEB128).
    // Before the fix, leb_128_size(128) returned 1 instead of 2, causing
    // the output buffer to be 1 byte too small → panic on slice indexing.
    #[test]
    fn packetize_obu_with_128_byte_payload_no_panic() {
        // Build a raw OBU: header (0x32 = frame, size present)
        // + LEB128 size (0x80, 0x01 = 128) + 128 bytes payload
        let mut payload = Vec::with_capacity(3 + 128);
        payload.push(0x32); // OBU header: frame type, size present
        payload.push(0x80); // LEB128 size byte 1: 128
        payload.push(0x01); // LEB128 size byte 2
        payload.extend(vec![0xAB; 128]); // 128 bytes of payload

        let mut packetizer = Av1Packetizer::default();
        let result = packetizer.packetize(1200, &payload);
        assert!(result.is_ok());
        let packets = result.unwrap();
        assert!(!packets.is_empty());
    }

    // Regression test: packetize an OBU that requires fragmentation across
    // multiple RTP packets, with exactly 128 bytes of payload.
    // This exercises both the leb_128_size fix (buffer allocation) and
    // the payload_offset fix (correct data in continuation fragments).
    #[test]
    fn packetize_128_byte_obu_fragmented_correctly() {
        // OBU: header + LEB128(128) + 128 bytes payload
        let mut payload = Vec::with_capacity(3 + 128);
        payload.push(0x32); // frame type, size present
        payload.push(0x80); // LEB128: 128
        payload.push(0x01);
        for i in 0u8..128 {
            payload.push(i); // distinguishable payload bytes
        }

        let mut packetizer = Av1Packetizer::default();
        // MTU of 50 forces fragmentation into multiple packets
        let result = packetizer.packetize(50, &payload);
        assert!(result.is_ok());
        let packets = result.unwrap();
        assert!(
            packets.len() >= 3,
            "128-byte OBU with MTU 50 should produce at least 3 packets"
        );

        // Verify round-trip: depacketize all packets and check payload integrity
        let mut out = Vec::new();
        let mut codec_extra = CodecExtra::None;
        let mut depacketizer = Av1Depacketizer::default();
        for pkt in &packets {
            let r = depacketizer.depacketize(pkt, &mut out, &mut codec_extra);
            assert!(r.is_ok(), "depacketize failed: {:?}", r);
        }
        // Output should be: OBU header (with size bit) + LEB128 size + payload
        // Find the payload portion and verify it matches
        assert!(
            out.len() >= 128,
            "round-tripped output too short: {} bytes",
            out.len()
        );
        // The payload bytes should appear in order at the end
        let payload_start = out.len() - 128;
        for i in 0u8..128 {
            assert_eq!(
                out[payload_start + i as usize],
                i,
                "payload byte {} mismatch after round-trip",
                i
            );
        }
    }

    // Regression test for the payload_offset bug in continuation fragments.
    // When an OBU with extension header spans multiple packets, the second
    // fragment used `obu_offset` instead of `payload_offset` to compute the
    // remaining payload size, causing incorrect data or panics.
    #[test]
    fn packetize_obu_with_extension_fragmented_round_trip() {
        // OBU with extension: header=0x36 (frame type + extension + size present),
        // ext_header=0x10, LEB128 size, then payload
        let mut raw = Vec::with_capacity(4 + 200);
        raw.push(0x36); // OBU header: frame, extension present, size present
        raw.push(0x10); // extension header
        raw.push(0xC8); // LEB128 size: 200
        raw.push(0x01);
        for i in 0u8..200 {
            raw.push(i);
        }

        let mut packetizer = Av1Packetizer::default();
        let result = packetizer.packetize(40, &raw);
        assert!(result.is_ok());
        let packets = result.unwrap();
        assert!(
            packets.len() >= 5,
            "200-byte OBU with MTU 40 should produce multiple packets"
        );

        // Round-trip through depacketizer
        let mut out = Vec::new();
        let mut codec_extra = CodecExtra::None;
        let mut depacketizer = Av1Depacketizer::default();
        for pkt in &packets {
            depacketizer
                .depacketize(pkt, &mut out, &mut codec_extra)
                .unwrap();
        }

        // Verify the 200-byte payload is intact
        let payload_start = out.len() - 200;
        for i in 0u8..200 {
            assert_eq!(
                out[payload_start + i as usize],
                i,
                "extension OBU payload byte {} corrupted after round-trip",
                i
            );
        }
    }

    #[test]
    fn test_detect_av1_keyframe() {
        // Empty
        assert!(!detect_av1_keyframe(&[]));

        // AV1 aggregation header: Z|Y|W W|N|reserved
        // N bit is bit 3 (0x08)

        // N=1 → keyframe
        assert!(detect_av1_keyframe(&[0x08]));
        assert!(detect_av1_keyframe(&[0x18])); // Z=0,Y=0,W=01,N=1
        assert!(detect_av1_keyframe(&[0x78])); // Z=0,Y=1,W=11,N=1
        assert!(detect_av1_keyframe(&[0x88])); // Z=1,Y=0,W=00,N=1
        assert!(detect_av1_keyframe(&[0x0F])); // N=1, reserved bits set

        // N=0 → not a keyframe
        assert!(!detect_av1_keyframe(&[0x00]));
        assert!(!detect_av1_keyframe(&[0x10])); // W=01, N=0
        assert!(!detect_av1_keyframe(&[0x70])); // Y=1, W=11, N=0
        assert!(!detect_av1_keyframe(&[0xF0])); // Z=1, Y=1, W=11, N=0
    }
}