Skip to main content

str0m/packet/
h264.rs

1#![allow(clippy::all)]
2
3use super::{CodecExtra, Depacketizer, PacketError, Packetizer};
4
5/// H264 information describing the depacketized / packetized data
6#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
7pub struct H264CodecExtra {
8    /// Flag which indicates that within [`MediaData`], there is an individual frame
9    /// containing complete and independent visual information. This frame serves
10    /// as a reference point for other frames in the video sequence.
11    ///
12    /// [`MediaData`]: crate::media::MediaData
13    pub is_keyframe: bool,
14}
15
16/// Packetizes H264 RTP packets.
17///
18/// ## Unversioned API surface
19///
20/// This struct is not currently versioned according to semver rules.
21/// Breaking changes may be made in minor or patch releases.
22#[derive(Default, Debug, Clone)]
23pub struct H264Packetizer {
24    sps_nalu: Option<Vec<u8>>,
25    pps_nalu: Option<Vec<u8>>,
26}
27
28pub const STAPA_NALU_TYPE: u8 = 24;
29pub const FUA_NALU_TYPE: u8 = 28;
30pub const FUB_NALU_TYPE: u8 = 29;
31pub const IDR_NALU_TYPE: u8 = 5;
32pub const SPS_NALU_TYPE: u8 = 7;
33pub const PPS_NALU_TYPE: u8 = 8;
34pub const AUD_NALU_TYPE: u8 = 9;
35#[allow(dead_code)] // Referenced by tests.
36pub const FILLER_NALU_TYPE: u8 = 12;
37
38pub const FUA_HEADER_SIZE: usize = 2;
39pub const STAPA_HEADER_SIZE: usize = 1;
40pub const STAPA_NALU_LENGTH_SIZE: usize = 2;
41
42pub const NALU_TYPE_BITMASK: u8 = 0x1F;
43pub const NALU_REF_IDC_BITMASK: u8 = 0x60;
44pub const FU_START_BITMASK: u8 = 0x80;
45pub const FU_END_BITMASK: u8 = 0x40;
46
47pub const OUTPUT_STAP_AHEADER: u8 = 0x78;
48
49pub static ANNEXB_NALUSTART_CODE: &[u8] = &[0x00, 0x00, 0x00, 0x01];
50
51/// Detect whether an H264 RTP payload contains a keyframe.
52///
53/// Checks for IDR (Instantaneous Decoding Refresh) NAL units (type 5)
54/// in the RTP payload.
55pub fn detect_h264_keyframe(payload: &[u8]) -> bool {
56    detect_h264_nalu(payload, IDR_NALU_TYPE)
57}
58
59/// Checks for target NAL units in the RTP payload.
60/// Handles single NAL units, STAP-A aggregation
61/// packets, and FU-A fragmentation units.
62///
63/// For FU-A packets, only the start fragment (S=1) is checked
64/// since the NAL type is only reliably available there.
65pub fn detect_h264_nalu(payload: &[u8], target_nalu: u8) -> bool {
66    if payload.is_empty() {
67        return false;
68    }
69
70    let nalu_type = payload[0] & NALU_TYPE_BITMASK;
71
72    match nalu_type {
73        // Single NAL unit (types 1-23)
74        1..=23 => nalu_type == target_nalu,
75
76        // STAP-A: check all aggregated NALUs
77        STAPA_NALU_TYPE => {
78            let mut offset = STAPA_HEADER_SIZE;
79            while offset + STAPA_NALU_LENGTH_SIZE <= payload.len() {
80                let nalu_size = ((payload[offset] as usize) << 8) | payload[offset + 1] as usize;
81                offset += STAPA_NALU_LENGTH_SIZE;
82                if offset + nalu_size > payload.len() {
83                    break;
84                }
85                if let Some(&b0) = payload.get(offset) {
86                    if b0 & NALU_TYPE_BITMASK == target_nalu {
87                        return true;
88                    }
89                }
90                offset += nalu_size;
91            }
92            false
93        }
94
95        // FU-A: check start fragment for IDR type
96        FUA_NALU_TYPE => {
97            if payload.len() < FUA_HEADER_SIZE {
98                return false;
99            }
100            let b1 = payload[1];
101            // Only the start fragment (S=1) reliably carries the original NAL type
102            if b1 & FU_START_BITMASK == 0 {
103                return false;
104            }
105            b1 & NALU_TYPE_BITMASK == target_nalu
106        }
107
108        _ => false,
109    }
110}
111
112impl H264Packetizer {
113    fn next_ind(nalu: &[u8], start: usize) -> (isize, isize) {
114        let mut zero_count = 0;
115
116        for (i, &b) in nalu[start..].iter().enumerate() {
117            if b == 0 {
118                zero_count += 1;
119                continue;
120            } else if b == 1 && zero_count >= 2 {
121                return ((start + i - zero_count) as isize, zero_count as isize + 1);
122            }
123            zero_count = 0
124        }
125        (-1, -1)
126    }
127
128    fn emit(&mut self, nalu: &[u8], mtu: usize, payloads: &mut Vec<Vec<u8>>) {
129        if nalu.is_empty() {
130            return;
131        }
132
133        let nalu_type = nalu[0] & NALU_TYPE_BITMASK;
134        let nalu_ref_idc = nalu[0] & NALU_REF_IDC_BITMASK;
135
136        if nalu_type == AUD_NALU_TYPE {
137            return;
138        } else if nalu_type == SPS_NALU_TYPE {
139            self.sps_nalu = Some(nalu.to_vec());
140            return;
141        } else if nalu_type == PPS_NALU_TYPE {
142            self.pps_nalu = Some(nalu.to_vec());
143            return;
144        } else if let (Some(sps_nalu), Some(pps_nalu)) = (&self.sps_nalu, &self.pps_nalu) {
145            // Pack current NALU with SPS and PPS as STAP-A
146            let sps_len = (sps_nalu.len() as u16).to_be_bytes();
147            let pps_len = (pps_nalu.len() as u16).to_be_bytes();
148
149            let mut stap_a_nalu = Vec::with_capacity(1 + 2 + sps_nalu.len() + 2 + pps_nalu.len());
150            stap_a_nalu.push(OUTPUT_STAP_AHEADER);
151            stap_a_nalu.extend(sps_len);
152            stap_a_nalu.extend_from_slice(sps_nalu);
153            stap_a_nalu.extend(pps_len);
154            stap_a_nalu.extend_from_slice(pps_nalu);
155            if stap_a_nalu.len() <= mtu {
156                payloads.push(stap_a_nalu);
157            }
158        }
159
160        if self.sps_nalu.is_some() && self.pps_nalu.is_some() {
161            self.sps_nalu = None;
162            self.pps_nalu = None;
163        }
164
165        // Single NALU
166        if nalu.len() <= mtu {
167            payloads.push(nalu.to_vec());
168            return;
169        }
170
171        // FU-A
172        let max_fragment_size = mtu as isize - FUA_HEADER_SIZE as isize;
173
174        // The FU payload consists of fragments of the payload of the fragmented
175        // NAL unit so that if the fragmentation unit payloads of consecutive
176        // FUs are sequentially concatenated, the payload of the fragmented NAL
177        // unit can be reconstructed.  The NAL unit type octet of the fragmented
178        // NAL unit is not included as such in the fragmentation unit payload,
179        // 	but rather the information of the NAL unit type octet of the
180        // fragmented NAL unit is conveyed in the F and NRI fields of the FU
181        // indicator octet of the fragmentation unit and in the type field of
182        // the FU header.  An FU payload MAY have any number of octets and MAY
183        // be empty.
184
185        let nalu_data = nalu;
186        // According to the RFC, the first octet is skipped due to redundant information
187        let mut nalu_data_index = 1;
188        let nalu_data_length = nalu.len() as isize - nalu_data_index;
189        let mut nalu_data_remaining = nalu_data_length;
190
191        if std::cmp::min(max_fragment_size, nalu_data_remaining) <= 0 {
192            return;
193        }
194
195        while nalu_data_remaining > 0 {
196            let current_fragment_size = std::cmp::min(max_fragment_size, nalu_data_remaining);
197            //out: = make([]byte, fuaHeaderSize + currentFragmentSize)
198            let mut out = Vec::with_capacity(FUA_HEADER_SIZE + current_fragment_size as usize);
199            // +---------------+
200            // |0|1|2|3|4|5|6|7|
201            // +-+-+-+-+-+-+-+-+
202            // |F|NRI|  Type   |
203            // +---------------+
204            let b0 = FUA_NALU_TYPE | nalu_ref_idc;
205            out.push(b0);
206
207            // +---------------+
208            //|0|1|2|3|4|5|6|7|
209            //+-+-+-+-+-+-+-+-+
210            //|S|E|R|  Type   |
211            //+---------------+
212
213            let mut b1 = nalu_type;
214            if nalu_data_remaining == nalu_data_length {
215                // Set start bit
216                b1 |= 1 << 7;
217            } else if nalu_data_remaining - current_fragment_size == 0 {
218                // Set end bit
219                b1 |= 1 << 6;
220            }
221            out.push(b1);
222
223            out.extend_from_slice(
224                &nalu_data
225                    [nalu_data_index as usize..(nalu_data_index + current_fragment_size) as usize],
226            );
227            payloads.push(out);
228
229            nalu_data_remaining -= current_fragment_size;
230            nalu_data_index += current_fragment_size;
231        }
232    }
233}
234
235impl Packetizer for H264Packetizer {
236    /// Payload fragments a H264 packet across one or more byte arrays
237    fn packetize(&mut self, mtu: usize, payload: &[u8]) -> Result<Vec<Vec<u8>>, PacketError> {
238        if payload.is_empty() || mtu == 0 {
239            return Ok(vec![]);
240        }
241
242        let mut payloads = vec![];
243
244        let (mut next_ind_start, mut next_ind_len) = H264Packetizer::next_ind(payload, 0);
245        if next_ind_start == -1 {
246            self.emit(payload, mtu, &mut payloads);
247        } else {
248            while next_ind_start != -1 {
249                let prev_start = (next_ind_start + next_ind_len) as usize;
250                let (next_ind_start2, next_ind_len2) =
251                    H264Packetizer::next_ind(payload, prev_start);
252                next_ind_start = next_ind_start2;
253                next_ind_len = next_ind_len2;
254                if next_ind_start != -1 {
255                    self.emit(
256                        &payload[prev_start..next_ind_start as usize],
257                        mtu,
258                        &mut payloads,
259                    );
260                } else {
261                    // Emit until end of stream, no end indicator found
262                    self.emit(&payload[prev_start..], mtu, &mut payloads);
263                }
264            }
265        }
266
267        Ok(payloads)
268    }
269
270    fn is_marker(&mut self, _data: &[u8], _previous: Option<&[u8]>, last: bool) -> bool {
271        last
272    }
273}
274
275/// Depacketizes H264 RTP packets.
276///
277/// ## Unversioned API surface
278///
279/// This struct is not currently versioned according to semver rules.
280/// Breaking changes may be made in minor or patch releases.
281#[derive(PartialEq, Eq, Debug, Default, Clone)]
282pub struct H264Depacketizer {
283    /// Whether to output in AVC format (length-prefixed NALUs) instead of Annex B format
284    pub is_avc: bool,
285    fua_buffer: Option<Vec<u8>>,
286}
287
288impl Depacketizer for H264Depacketizer {
289    fn out_size_hint(&self, packets_size: usize) -> Option<usize> {
290        // Roughly account for Annex B start codes or AVC length prefixes.
291        let estimated_packets = (packets_size / 1200).saturating_add(1);
292        Some(packets_size.saturating_add(4usize.saturating_mul(estimated_packets)))
293    }
294
295    /// depacketize parses the passed byte slice and stores the result in the
296    /// H264Packet this method is called upon
297    fn depacketize(
298        &mut self,
299        packet: &[u8],
300        out: &mut Vec<u8>,
301        extra: &mut CodecExtra,
302    ) -> Result<(), PacketError> {
303        if packet.len() == 0 {
304            return Err(PacketError::ErrShortPacket);
305        }
306
307        // NALU Types
308        // https://tools.ietf.org/html/rfc6184#section-5.4
309        let b0 = packet[0];
310        let nalu_type = b0 & NALU_TYPE_BITMASK;
311
312        match nalu_type {
313            t @ 1..=23 => {
314                let is_keyframe = if let CodecExtra::H264(e) = extra {
315                    (t == IDR_NALU_TYPE) | e.is_keyframe
316                } else {
317                    t == IDR_NALU_TYPE
318                };
319                *extra = CodecExtra::H264(H264CodecExtra { is_keyframe });
320
321                if self.is_avc {
322                    out.extend_from_slice(&(packet.len() as u32).to_be_bytes());
323                } else {
324                    out.extend_from_slice(ANNEXB_NALUSTART_CODE);
325                }
326                out.extend_from_slice(packet);
327                Ok(())
328            }
329            STAPA_NALU_TYPE => {
330                let mut curr_offset = STAPA_HEADER_SIZE;
331                while curr_offset + 1 < packet.len() {
332                    let nalu_size =
333                        ((packet[curr_offset] as usize) << 8) | packet[curr_offset + 1] as usize;
334                    curr_offset += STAPA_NALU_LENGTH_SIZE;
335
336                    if curr_offset + nalu_size > packet.len() {
337                        return Err(PacketError::StapASizeLargerThanBuffer(
338                            nalu_size,
339                            packet.len() - curr_offset,
340                        ));
341                    }
342
343                    let Some(b0) = packet.get(curr_offset) else {
344                        continue;
345                    };
346                    let t = b0 & NALU_TYPE_BITMASK;
347                    let is_keyframe = if let CodecExtra::H264(e) = extra {
348                        (t == IDR_NALU_TYPE) | e.is_keyframe
349                    } else {
350                        t == IDR_NALU_TYPE
351                    };
352                    *extra = CodecExtra::H264(H264CodecExtra { is_keyframe });
353
354                    if self.is_avc {
355                        out.extend_from_slice(&(nalu_size as u32).to_be_bytes());
356                    } else {
357                        out.extend_from_slice(ANNEXB_NALUSTART_CODE);
358                    }
359                    out.extend_from_slice(&packet[curr_offset..curr_offset + nalu_size]);
360                    curr_offset += nalu_size;
361                }
362
363                Ok(())
364            }
365            FUA_NALU_TYPE => {
366                if packet.len() < FUA_HEADER_SIZE as usize {
367                    return Err(PacketError::ErrShortPacket);
368                }
369
370                if self.fua_buffer.is_none() {
371                    self.fua_buffer = Some(Vec::new());
372                }
373
374                if let Some(fua_buffer) = &mut self.fua_buffer {
375                    fua_buffer.extend_from_slice(&packet[FUA_HEADER_SIZE as usize..]);
376                }
377
378                let b1 = packet[1];
379                if b1 & FU_END_BITMASK != 0 {
380                    let nalu_ref_idc = b0 & NALU_REF_IDC_BITMASK;
381                    let fragmented_nalu_type = b1 & NALU_TYPE_BITMASK;
382
383                    let is_keyframe = if let CodecExtra::H264(e) = extra {
384                        (fragmented_nalu_type == IDR_NALU_TYPE) | e.is_keyframe
385                    } else {
386                        fragmented_nalu_type == IDR_NALU_TYPE
387                    };
388                    *extra = CodecExtra::H264(H264CodecExtra { is_keyframe });
389
390                    if let Some(fua_buffer) = self.fua_buffer.take() {
391                        if self.is_avc {
392                            out.extend_from_slice(&((fua_buffer.len() + 1) as u32).to_be_bytes());
393                        } else {
394                            out.extend_from_slice(ANNEXB_NALUSTART_CODE);
395                        }
396                        out.push(nalu_ref_idc | fragmented_nalu_type);
397                        out.extend_from_slice(&fua_buffer);
398                    }
399
400                    Ok(())
401                } else {
402                    Ok(())
403                }
404            }
405            _ => Err(PacketError::NaluTypeIsNotHandled(nalu_type)),
406        }
407    }
408
409    /// is_partition_head checks if this is the head of a packetized nalu stream.
410    fn is_partition_head(&self, packet: &[u8]) -> bool {
411        if packet.len() < 2 {
412            return false;
413        }
414
415        if packet[0] & NALU_TYPE_BITMASK == FUA_NALU_TYPE
416            || packet[0] & NALU_TYPE_BITMASK == FUB_NALU_TYPE
417        {
418            (packet[1] & FU_START_BITMASK) != 0
419        } else {
420            true
421        }
422    }
423
424    fn is_partition_tail(&self, marker: bool, _packet: &[u8]) -> bool {
425        marker
426    }
427}
428
429#[cfg(test)]
430mod test {
431    use super::*;
432
433    #[test]
434    fn test_h264_payload() -> Result<(), PacketError> {
435        let empty = &[];
436        let small_payload = &[0x90, 0x90, 0x90];
437        let multiple_payload = &[0x00, 0x00, 0x01, 0x90, 0x00, 0x00, 0x01, 0x90];
438        let large_payload = &[
439            0x00, 0x00, 0x01, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10,
440            0x11, 0x12, 0x13, 0x14, 0x15,
441        ];
442        let large_payload_packetized = vec![
443            &[0x1c, 0x80, 0x01, 0x02, 0x03],
444            &[0x1c, 0x00, 0x04, 0x05, 0x06],
445            &[0x1c, 0x00, 0x07, 0x08, 0x09],
446            &[0x1c, 0x00, 0x10, 0x11, 0x12],
447            &[0x1c, 0x40, 0x13, 0x14, 0x15],
448        ];
449
450        let mut pck = H264Packetizer::default();
451
452        // Positive MTU, empty payload
453        let result = pck.packetize(1, empty)?;
454        assert!(result.is_empty(), "Generated payload should be empty");
455
456        // 0 MTU, small payload
457        let result = pck.packetize(0, small_payload)?;
458        assert_eq!(result.len(), 0, "Generated payload should be empty");
459
460        // Positive MTU, small payload
461        let result = pck.packetize(1, small_payload)?;
462        assert_eq!(result.len(), 0, "Generated payload should be empty");
463
464        // Positive MTU, small payload
465        let result = pck.packetize(5, small_payload)?;
466        assert_eq!(result.len(), 1, "Generated payload should be the 1");
467        assert_eq!(
468            result[0].len(),
469            small_payload.len(),
470            "Generated payload should be the same size as original payload size"
471        );
472
473        // Multiple NALU in a single payload
474        let result = pck.packetize(5, multiple_payload)?;
475        assert_eq!(result.len(), 2, "2 nal units should be broken out");
476        for i in 0..2 {
477            assert_eq!(
478                result[i].len(),
479                1,
480                "Payload {} of 2 is packed incorrectly",
481                i + 1,
482            );
483        }
484
485        // Large Payload split across multiple RTP Packets
486        let result = pck.packetize(5, large_payload)?;
487        assert_eq!(
488            result, large_payload_packetized,
489            "FU-A packetization failed"
490        );
491
492        // Nalu type 9
493        let small_payload2 = &[0x09, 0x00, 0x00];
494        let result = pck.packetize(5, small_payload2)?;
495        assert_eq!(result.len(), 0, "Generated payload should be empty");
496
497        // Nalu type 12
498        let filler_payload = &[FILLER_NALU_TYPE, 0xff, 0x80];
499        let result = pck.packetize(5, filler_payload)?;
500        assert_eq!(result, vec![filler_payload], "Filler NALU should be kept");
501
502        Ok(())
503    }
504
505    macro_rules! test_h264 {
506        ($name:tt, $is_avc:expr, $is_ok: expr, $payload:expr, $err:tt) => {
507            #[test]
508            fn $name() -> Result<(), PacketError> {
509                let mut pkt = H264Depacketizer::default();
510                pkt.is_avc = $is_avc;
511                let mut extra = CodecExtra::None;
512                let mut out: Vec<u8> = Vec::new();
513                let result = pkt.depacketize($payload, &mut out, &mut extra);
514                if $is_ok {
515                    assert!(result.is_ok(), $err);
516                } else {
517                    assert!(result.is_err(), $err);
518                }
519                Ok(())
520            }
521        };
522    }
523
524    test_h264!(
525        nil_payload,
526        false,
527        false,
528        &[],
529        "Unmarshal did not fail on nil payload"
530    );
531    test_h264!(
532        unit_delimiter,
533        false,
534        true,
535        &[0x09, 0x30],
536        "Unmarshal should accept minimal h.264 access unit delimiter"
537    );
538    test_h264!(
539        end_of_sequence_nalu,
540        false,
541        true,
542        &[0x0A],
543        "Unmarshal should accept end of sequence NALU"
544    );
545    test_h264!(
546        not_handled,
547        false,
548        false,
549        &[0xFF, 0x00, 0x00],
550        "Unmarshal accepted a packet with a NALU Type we don't handle"
551    );
552    test_h264!(
553        incomplete_single_payload_multi_nalu,
554        false,
555        false,
556        &[
557            0x78, 0x00, 0x0f, 0x67, 0x42, 0xc0, 0x1f, 0x1a, 0x32, 0x35, 0x01, 0x40, 0x7a, 0x40,
558            0x3c, 0x22, 0x11,
559        ],
560        "Unmarshal accepted a STAP-A packet with insufficient data"
561    );
562
563    #[test]
564    fn single_payload() -> Result<(), PacketError> {
565        let mut pkt = H264Depacketizer::default();
566        let mut extra = CodecExtra::None;
567        let mut out: Vec<u8> = Vec::new();
568        let single_payload = &[0x90, 0x90, 0x90];
569        let _ = pkt.depacketize(single_payload, &mut out, &mut extra);
570        let single_payload_unmarshaled = &[0x00, 0x00, 0x00, 0x01, 0x90, 0x90, 0x90];
571        assert_eq!(
572            out, single_payload_unmarshaled,
573            "Unmarshaling a single payload shouldn't modify the payload"
574        );
575        Ok(())
576    }
577
578    #[test]
579    fn single_payload_avc() -> Result<(), PacketError> {
580        let mut pkt = H264Depacketizer::default();
581        pkt.is_avc = true;
582        let mut extra = CodecExtra::None;
583        let mut out: Vec<u8> = Vec::new();
584        let single_payload = &[0x90, 0x90, 0x90];
585        let _ = pkt.depacketize(single_payload, &mut out, &mut extra);
586        let single_payload_unmarshaled_avc = &[0x00, 0x00, 0x00, 0x03, 0x90, 0x90, 0x90];
587        assert_eq!(
588            out, single_payload_unmarshaled_avc,
589            "Unmarshaling a single payload into avc stream shouldn't modify the payload"
590        );
591        Ok(())
592    }
593
594    #[test]
595    fn h264_large_out() -> Result<(), PacketError> {
596        let large_payload_packetized = vec![
597            &[0x1c, 0x80, 0x01, 0x02, 0x03],
598            &[0x1c, 0x00, 0x04, 0x05, 0x06],
599            &[0x1c, 0x00, 0x07, 0x08, 0x09],
600            &[0x1c, 0x00, 0x10, 0x11, 0x12],
601            &[0x1c, 0x40, 0x13, 0x14, 0x15],
602        ];
603
604        let large_payload = &[
605            0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09,
606            0x10, 0x11, 0x12, 0x13, 0x14, 0x15,
607        ];
608
609        let mut pkt = H264Depacketizer::default();
610        let mut extra = CodecExtra::None;
611
612        let mut large_out = Vec::new();
613        for p in &large_payload_packetized {
614            pkt.depacketize(*p, &mut large_out, &mut extra)?;
615        }
616        assert_eq!(
617            large_out, large_payload,
618            "Failed to unmarshal a large payload"
619        );
620
621        Ok(())
622    }
623
624    #[test]
625    fn h264_large_out_avc() -> Result<(), PacketError> {
626        let large_payload_packetized = vec![
627            &[0x1c, 0x80, 0x01, 0x02, 0x03],
628            &[0x1c, 0x00, 0x04, 0x05, 0x06],
629            &[0x1c, 0x00, 0x07, 0x08, 0x09],
630            &[0x1c, 0x00, 0x10, 0x11, 0x12],
631            &[0x1c, 0x40, 0x13, 0x14, 0x15],
632        ];
633
634        let large_payload_avc = &[
635            0x00, 0x00, 0x00, 0x10, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09,
636            0x10, 0x11, 0x12, 0x13, 0x14, 0x15,
637        ];
638
639        let mut avc_pkt = H264Depacketizer {
640            is_avc: true,
641            ..Default::default()
642        };
643
644        let mut extra = CodecExtra::None;
645
646        let mut large_out_avc = Vec::new();
647        for p in &large_payload_packetized {
648            avc_pkt.depacketize(*p, &mut large_out_avc, &mut extra)?;
649        }
650        assert_eq!(
651            large_out_avc, large_payload_avc,
652            "Failed to unmarshal a large payload into avc stream"
653        );
654
655        Ok(())
656    }
657
658    #[test]
659    fn single_payload_multi_nalu() -> Result<(), PacketError> {
660        let single_payload_multi_nalu = &[
661            0x78, 0x00, 0x0f, 0x67, 0x42, 0xc0, 0x1f, 0x1a, 0x32, 0x35, 0x01, 0x40, 0x7a, 0x40,
662            0x3c, 0x22, 0x11, 0xa8, 0x00, 0x05, 0x68, 0x1a, 0x34, 0xe3, 0xc8, 0x00,
663        ];
664        let single_payload_multi_nalu_unmarshaled = &[
665            0x00, 0x00, 0x00, 0x01, 0x67, 0x42, 0xc0, 0x1f, 0x1a, 0x32, 0x35, 0x01, 0x40, 0x7a,
666            0x40, 0x3c, 0x22, 0x11, 0xa8, 0x00, 0x00, 0x00, 0x01, 0x68, 0x1a, 0x34, 0xe3, 0xc8,
667        ];
668
669        let mut pkt = H264Depacketizer::default();
670
671        let mut extra = CodecExtra::None;
672
673        let mut out = Vec::new();
674        pkt.depacketize(single_payload_multi_nalu, &mut out, &mut extra)?;
675        assert_eq!(
676            out, single_payload_multi_nalu_unmarshaled,
677            "Failed to unmarshal a single packet with multiple NALUs"
678        );
679
680        Ok(())
681    }
682
683    #[test]
684    fn single_payload_multi_nalu_avc() -> Result<(), PacketError> {
685        let single_payload_multi_nalu = &[
686            0x78, 0x00, 0x0f, 0x67, 0x42, 0xc0, 0x1f, 0x1a, 0x32, 0x35, 0x01, 0x40, 0x7a, 0x40,
687            0x3c, 0x22, 0x11, 0xa8, 0x00, 0x05, 0x68, 0x1a, 0x34, 0xe3, 0xc8, 0x00,
688        ];
689        let single_payload_multi_nalu_unmarshaled_avc = &[
690            0x00, 0x00, 0x00, 0x0f, 0x67, 0x42, 0xc0, 0x1f, 0x1a, 0x32, 0x35, 0x01, 0x40, 0x7a,
691            0x40, 0x3c, 0x22, 0x11, 0xa8, 0x00, 0x00, 0x00, 0x05, 0x68, 0x1a, 0x34, 0xe3, 0xc8,
692        ];
693
694        let mut avc_pkt = H264Depacketizer::default();
695        avc_pkt.is_avc = true;
696
697        let mut extra = CodecExtra::None;
698
699        let mut out = Vec::new();
700        avc_pkt.depacketize(single_payload_multi_nalu, &mut out, &mut extra)?;
701        assert_eq!(
702            out, single_payload_multi_nalu_unmarshaled_avc,
703            "Failed to unmarshal a single packet with multiple NALUs into avc stream"
704        );
705
706        Ok(())
707    }
708
709    #[test]
710    fn test_h264_partition_head_checker_is_partition_head() -> Result<(), PacketError> {
711        let h264 = H264Depacketizer::default();
712        let empty_nalu = &[];
713        assert!(
714            !h264.is_partition_head(empty_nalu),
715            "empty nalu must not be a partition head"
716        );
717
718        let single_nalu = &[1, 0];
719        assert!(
720            h264.is_partition_head(single_nalu),
721            "single nalu must be a partition head"
722        );
723
724        let stapa_nalu = &[STAPA_NALU_TYPE, 0];
725        assert!(
726            h264.is_partition_head(stapa_nalu),
727            "stapa nalu must be a partition head"
728        );
729
730        let fua_start_nalu = &[FUA_NALU_TYPE, FU_START_BITMASK];
731        assert!(
732            h264.is_partition_head(fua_start_nalu),
733            "fua start nalu must be a partition head"
734        );
735
736        let fua_end_nalu = &[FUA_NALU_TYPE, FU_END_BITMASK];
737        assert!(
738            !h264.is_partition_head(fua_end_nalu),
739            "fua end nalu must not be a partition head"
740        );
741
742        let fub_start_nalu = &[FUB_NALU_TYPE, FU_START_BITMASK];
743        assert!(
744            h264.is_partition_head(fub_start_nalu),
745            "fub start nalu must be a partition head"
746        );
747
748        let fub_end_nalu = &[FUB_NALU_TYPE, FU_END_BITMASK];
749        assert!(
750            !h264.is_partition_head(fub_end_nalu),
751            "fub end nalu must not be a partition head"
752        );
753
754        Ok(())
755    }
756
757    #[test]
758    fn test_h264_packetizer_payload_sps_and_pps_handling() -> Result<(), PacketError> {
759        let mut pck = H264Packetizer::default();
760        let expected: Vec<&[u8]> = vec![
761            &[
762                0x78, 0x00, 0x03, 0x07, 0x00, 0x01, 0x00, 0x03, 0x08, 0x02, 0x03,
763            ],
764            &[0x05, 0x04, 0x05],
765        ];
766
767        // When packetizing SPS and PPS are emitted with following NALU
768        let res = pck.packetize(1500, &[0x07, 0x00, 0x01])?;
769        assert!(res.is_empty(), "Generated payload should be empty");
770
771        let res = pck.packetize(1500, &[0x08, 0x02, 0x03])?;
772        assert!(res.is_empty(), "Generated payload should be empty");
773
774        let actual = pck.packetize(1500, &[0x05, 0x04, 0x05])?;
775        assert_eq!(actual, expected, "SPS and PPS aren't packed together");
776
777        Ok(())
778    }
779
780    #[test]
781    fn test_h264_depacketizer_idr_handling() -> Result<(), PacketError> {
782        let mut pck = H264Depacketizer::default();
783        let mut extra = CodecExtra::None;
784        let mut out = vec![];
785
786        // First byte is NALU type
787        let packet = [0x85];
788        pck.depacketize(&packet, &mut out, &mut extra)?;
789        let CodecExtra::H264(e) = extra else {
790            panic!("Expected CodecExtra::H264");
791        };
792        assert!(e.is_keyframe);
793
794        // First byte is STAPA NALU type
795        let packet = vec![
796            vec![
797                120, 0, 15, 103, 66, 192, 21, 140, 141, 64, 160, 203, 207, 0, 240, 136, 70, 160, 0,
798                4, 104, 206, 60, 128, 1, 20, 101,
799            ],
800            vec![0; 276],
801        ]
802        .into_iter()
803        .flatten()
804        .collect::<Vec<_>>();
805        pck.depacketize(packet.as_slice(), &mut out, &mut extra)?;
806        let CodecExtra::H264(e) = extra else {
807            panic!("Expected CodecExtra::H264");
808        };
809        assert!(e.is_keyframe);
810
811        // First byte is FUA NALU type
812        let packet = [124, 69];
813        pck.depacketize(&packet, &mut out, &mut extra)?;
814        let CodecExtra::H264(e) = extra else {
815            panic!("Expected CodecExtra::H264");
816        };
817        assert!(e.is_keyframe);
818        Ok(())
819    }
820
821    #[test]
822    fn parse_first_packet() {
823        const PACKET: &[u8] = &[
824            120, 000, 015, 103, 066, 192, 021, 140, 141, 064, 160, 203, 207, 000, 240, 136, 070,
825            160, 000, 004, 104, 206, 060, 128, 000, 204, 101, 184, 000, 004, 000, 000, 005, 057,
826            049, 064, 000, 064, 222, 078, 078, 078, 078, 078, 078, 078, 078, 078, 078, 078, 078,
827            078, 078, 078, 078, 078, 078, 078, 186, 235, 174, 186, 235, 174, 186, 235, 174, 186,
828            235, 174, 186, 235, 174, 186, 235, 174, 186, 235, 174, 186, 235, 174, 186, 235, 174,
829            186, 235, 174, 186, 235, 174, 186, 235, 174, 186, 235, 173, 223, 039, 125, 247, 223,
830            125, 245, 215, 093, 117, 215, 093, 117, 214, 239, 174, 187, 235, 174, 186, 235, 174,
831            186, 235, 174, 186, 235, 174, 186, 235, 174, 186, 235, 174, 186, 235, 174, 186, 235,
832            174, 186, 235, 174, 183, 093, 117, 215, 093, 117, 215, 093, 117, 215, 093, 117, 215,
833            093, 117, 215, 093, 117, 215, 092, 189, 117, 215, 093, 117, 215, 093, 117, 215, 093,
834            117, 215, 093, 117, 215, 093, 117, 215, 093, 117, 214, 239, 190, 251, 239, 190, 186,
835            235, 174, 186, 235, 174, 186, 235, 174, 186, 235, 174, 186, 235, 174, 186, 235, 174,
836            186, 235, 174, 186, 235, 175, 227, 255, 240, 247, 021, 223, 125, 247, 223, 125, 247,
837            223, 125, 247, 223, 125, 247, 223, 125, 248,
838        ];
839
840        let mut pck = H264Depacketizer::default();
841        let mut extra = CodecExtra::None;
842        let mut out = vec![];
843        pck.depacketize(PACKET, &mut out, &mut extra).unwrap();
844    }
845
846    #[test]
847    fn test_out_of_bounds_access() {
848        const PACKET: &[u8] = &[STAPA_NALU_TYPE, 0x00, 0x00];
849
850        let mut pck = H264Depacketizer::default();
851        let mut extra = CodecExtra::None;
852        let mut out = vec![];
853        pck.depacketize(PACKET, &mut out, &mut extra).unwrap();
854    }
855
856    #[test]
857    fn test_detect_h264_keyframe() {
858        // Empty payload
859        assert!(!detect_h264_keyframe(&[]));
860
861        // Single IDR NAL unit (type 5)
862        assert!(detect_h264_keyframe(&[0x65, 0x00, 0x00])); // 0x65 & 0x1F = 5
863
864        // Single non-IDR NAL unit (type 1 = coded slice)
865        assert!(!detect_h264_keyframe(&[0x41, 0x00, 0x00])); // 0x41 & 0x1F = 1
866
867        // SPS (type 7) - not a keyframe
868        assert!(!detect_h264_keyframe(&[0x67, 0x00, 0x00]));
869
870        // PPS (type 8) - not a keyframe
871        assert!(!detect_h264_keyframe(&[0x68, 0x00, 0x00]));
872
873        // STAP-A containing IDR
874        // Header: type 24 (STAP-A)
875        // NALU 1: 2 bytes, type 7 (SPS)
876        // NALU 2: 2 bytes, type 5 (IDR)
877        let stapa_with_idr = [
878            0x18, // STAP-A (24)
879            0x00, 0x02, 0x67, 0xAA, // SPS: size=2, type=7
880            0x00, 0x02, 0x65, 0xBB, // IDR: size=2, type=5
881        ];
882        assert!(detect_h264_keyframe(&stapa_with_idr));
883
884        // STAP-A without IDR
885        let stapa_no_idr = [
886            0x18, // STAP-A (24)
887            0x00, 0x02, 0x67, 0xAA, // SPS: size=2, type=7
888            0x00, 0x02, 0x68, 0xBB, // PPS: size=2, type=8
889        ];
890        assert!(!detect_h264_keyframe(&stapa_no_idr));
891
892        // FU-A start fragment with IDR type
893        let fua_start_idr = [
894            0x7C, // FU indicator: type=28 (FU-A)
895            0x85, // FU header: S=1, type=5 (IDR)
896            0x00, 0x00,
897        ];
898        assert!(detect_h264_keyframe(&fua_start_idr));
899
900        // FU-A start fragment with non-IDR type
901        let fua_start_non_idr = [
902            0x7C, // FU indicator: type=28 (FU-A)
903            0x81, // FU header: S=1, type=1 (non-IDR)
904            0x00, 0x00,
905        ];
906        assert!(!detect_h264_keyframe(&fua_start_non_idr));
907
908        // FU-A continuation fragment (S=0) - cannot detect
909        let fua_continuation = [
910            0x7C, // FU indicator: type=28 (FU-A)
911            0x05, // FU header: S=0, type=5 (IDR) but S=0
912            0x00, 0x00,
913        ];
914        assert!(!detect_h264_keyframe(&fua_continuation));
915
916        // FU-A too short
917        assert!(!detect_h264_keyframe(&[0x7C]));
918    }
919
920    #[test]
921    fn test_detect_h264_nalu() {
922        // Empty payload
923        assert!(!detect_h264_nalu(&[], SPS_NALU_TYPE));
924
925        // SPS (type 7)
926        assert!(detect_h264_nalu(&[0x67, 0x00, 0x00], SPS_NALU_TYPE));
927
928        // PPS (type 8)
929        assert!(!detect_h264_nalu(&[0x68, 0x00, 0x00], SPS_NALU_TYPE));
930
931        // STAP-A containing IDR
932        // Header: type 24 (STAP-A)
933        // NALU 1: 2 bytes, type 7 (SPS)
934        // NALU 2: 2 bytes, type 5 (IDR)
935        let stapa_with_idr = [
936            0x18, // STAP-A (24)
937            0x00, 0x02, 0x67, 0xAA, // SPS: size=2, type=7
938            0x00, 0x02, 0x65, 0xBB, // IDR: size=2, type=5
939        ];
940        assert!(detect_h264_nalu(&stapa_with_idr, SPS_NALU_TYPE));
941
942        // STAP-A without IDR
943        let stapa_no_idr = [
944            0x18, // STAP-A (24)
945            0x00, 0x02, 0x67, 0xAA, // SPS: size=2, type=7
946            0x00, 0x02, 0x68, 0xBB, // PPS: size=2, type=8
947        ];
948        assert!(detect_h264_nalu(&stapa_no_idr, SPS_NALU_TYPE));
949
950        // FU-A too short
951        assert!(!detect_h264_nalu(&[0x7C], SPS_NALU_TYPE));
952    }
953
954    #[test]
955    fn packetize_respects_mtu() -> Result<(), PacketError> {
956        // NAL header byte (type=5, IDR slice) + payload.
957        let mut payload = vec![0x05u8];
958        payload.extend(std::iter::repeat(0xABu8).take(2000));
959        for &mtu in &[100usize, 300, 600, 1200] {
960            let mut pck = H264Packetizer::default();
961            let pkts = pck.packetize(mtu, &payload)?;
962            assert!(!pkts.is_empty(), "H264 produced no packets at mtu {mtu}");
963            for (i, pkt) in pkts.iter().enumerate() {
964                assert!(
965                    pkt.len() <= mtu,
966                    "H264 packet {i} size {} > mtu {mtu}",
967                    pkt.len()
968                );
969            }
970        }
971        Ok(())
972    }
973}