Skip to main content

str0m/packet/
h265.rs

1#![allow(clippy::all)]
2#![allow(unused)]
3
4use super::{CodecExtra, Depacketizer, PacketError, Packetizer};
5use arrayvec::ArrayVec;
6use tracing::warn;
7
8/// H265 (HEVC) information describing the depacketized / packetized data.
9#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
10pub struct H265CodecExtra {
11    /// Flag which indicates that within [`MediaData`], there is an individual frame
12    /// containing complete and independent visual information. This frame serves
13    /// as a reference point for other frames in the video sequence.
14    ///
15    /// [`MediaData`]: crate::media::MediaData
16    pub is_keyframe: bool,
17}
18
19///
20/// Network Abstraction Unit Header implementation
21///
22
23const H265NALU_HEADER_SIZE: usize = 2;
24/// https://datatracker.ietf.org/doc/html/rfc7798#section-4.4.2
25const H265NALU_AGGREGATION_PACKET_TYPE: u8 = 48;
26/// https://datatracker.ietf.org/doc/html/rfc7798#section-4.4.3
27const H265NALU_FRAGMENTATION_UNIT_TYPE: u8 = 49;
28/// https://datatracker.ietf.org/doc/html/rfc7798#section-4.4.4
29const H265NALU_PACI_PACKET_TYPE: u8 = 50;
30/// Maximum PHES (Payload Header Extension Structure) size in PACI packets (RFC 7798 §4.4.4)
31const H265PACI_MAX_PHES_SIZE: usize = 31;
32
33// HEVC NAL unit type values as defined by the H.265 / HEVC bitstream specification,
34// ITU-T Rec. H.265 | ISO/IEC 23008-2, clause 7.4.2.2 ("NAL unit header semantics"),
35// Table 7-1 (NAL unit type assignments).
36const H265NALU_VPS_NALU_TYPE: u8 = 32;
37const H265NALU_SPS_NALU_TYPE: u8 = 33;
38const H265NALU_PPS_NALU_TYPE: u8 = 34;
39const H265NALU_AUD_NALU_TYPE: u8 = 35;
40const H265NALU_FILLER_NALU_TYPE: u8 = 38;
41
42// IRAP (Intra Random Access Point) NAL unit types - keyframes/random access points
43// BLA (Broken Link Access) pictures.
44const H265NALU_BLA_W_LP: u8 = 16;
45const H265NALU_BLA_W_RADL: u8 = 17;
46const H265NALU_BLA_N_LP: u8 = 18;
47// IDR (Instantaneous Decoding Refresh) pictures.
48const H265NALU_IDR_W_RADL: u8 = 19;
49const H265NALU_IDR_N_LP: u8 = 20;
50// CRA (Clean Random Access) picture.
51const H265NALU_CRA_NUT: u8 = 21;
52
53pub static ANNEXB_NALUSTART_CODE: &[u8] = &[0x00, 0x00, 0x00, 0x01];
54
55/// Detect whether an H265 (HEVC) RTP payload contains a keyframe.
56///
57/// Checks for IRAP (Intra Random Access Point) NAL units in the RTP payload.
58/// IRAP types include BLA (16-18), IDR (19-20), and CRA (21).
59///
60/// Handles single NAL units, aggregation packets (AP, type 48),
61/// and fragmentation units (FU, type 49).
62///
63/// For FU packets, only the start fragment (S=1) is detected as a
64/// keyframe since the original NAL type is in the FU header.
65pub fn detect_h265_keyframe(payload: &[u8]) -> bool {
66    if payload.len() < H265NALU_HEADER_SIZE {
67        return false;
68    }
69
70    let header = H265NALUHeader::new(payload[0], payload[1]);
71    let nalu_type = header.nalu_type();
72
73    match nalu_type {
74        // Single NAL unit (types 0-47)
75        0..=47 => header.is_irap(),
76
77        // Aggregation packet: check all aggregated NALUs
78        H265NALU_AGGREGATION_PACKET_TYPE => {
79            let mut offset = H265NALU_HEADER_SIZE;
80            while offset + 2 <= payload.len() {
81                let nalu_size = ((payload[offset] as usize) << 8) | payload[offset + 1] as usize;
82                offset += 2;
83                if offset + nalu_size > payload.len() || nalu_size < H265NALU_HEADER_SIZE {
84                    break;
85                }
86                let inner = H265NALUHeader::new(payload[offset], payload[offset + 1]);
87                if inner.is_irap() {
88                    return true;
89                }
90                offset += nalu_size;
91            }
92            false
93        }
94
95        // Fragmentation unit: check FU header for original NAL type
96        H265NALU_FRAGMENTATION_UNIT_TYPE => {
97            // FU header is byte 2 (after 2-byte NAL header)
98            if payload.len() < H265NALU_HEADER_SIZE + 1 {
99                return false;
100            }
101            let fu_header = payload[H265NALU_HEADER_SIZE];
102            // S bit (start fragment) is bit 7
103            if fu_header & 0x80 == 0 {
104                return false;
105            }
106            // FU type is lower 6 bits
107            let fu_type = fu_header & 0x3F;
108            matches!(
109                fu_type,
110                H265NALU_BLA_W_LP
111                    | H265NALU_BLA_W_RADL
112                    | H265NALU_BLA_N_LP
113                    | H265NALU_IDR_W_RADL
114                    | H265NALU_IDR_N_LP
115                    | H265NALU_CRA_NUT
116            )
117        }
118
119        _ => false,
120    }
121}
122
123/// Packetizes H265 (HEVC) RTP payloads.
124///
125/// This implements the packetization rules from RFC 7798.
126///
127/// Supported output payload types:
128/// - Single NAL Unit packets (one NAL unit per RTP payload)
129/// - Fragmentation Units (FU, type 49) for NAL units larger than the MTU
130/// - Aggregation Packets (AP, type 48) for parameter sets (VPS/SPS/PPS)
131///
132/// The packetizer caches VPS, SPS, and PPS NAL units and emits them together
133/// in a single Aggregation Packet (AP) immediately before the next non-parameter-set
134/// NAL unit, as recommended by RFC 7798.
135///
136/// ## Input format
137///
138/// The input `payload` may be either:
139/// - A single NAL unit (starting with the 2-byte HEVC NAL unit header), OR
140/// - An Annex-B bytestream containing one or more NAL units separated by start codes
141///   (`0x00 00 01` or `0x00 00 00 01`).
142///
143/// Start codes are stripped from the output RTP payloads.
144
145/// Safe maximum RTP payload for real-world WebRTC (avoids IP fragmentation).
146const MAX_PACKET_SIZE: usize = 1200;
147
148/// Minimum FU payload size - at least 1 byte of actual NAL data required.
149const MIN_FU_PAYLOAD: usize = 1;
150
151/// Minimum MTU for H.265 fragmentation.
152/// Calculated as: NALU header (2 bytes) + FU header (1 byte) + minimum payload (1 byte) = 4 bytes total.
153/// Any MTU smaller than this cannot accommodate even a single fragmentation unit.
154const MIN_MTU: usize = H265NALU_HEADER_SIZE + H265FRAGMENTATION_UNIT_HEADER_SIZE + MIN_FU_PAYLOAD;
155
156#[derive(Debug, Clone)]
157pub struct H265Packetizer {
158    // Parameter sets: heap-allocated but set once per stream (cold path).
159    vps_nalu: Option<Vec<u8>>,
160    sps_nalu: Option<Vec<u8>>,
161    pps_nalu: Option<Vec<u8>>,
162    // Reusable packet buffer - heap allocated once, reused for zero-allocation hot path.
163    // This is reused on every fragment, avoiding N allocations per frame.
164    // Using Vec instead of ArrayVec since MAX_PACKET_SIZE (1200) is too large for stack.
165    pkt_buf: Vec<u8>,
166    // DONL (Decoding Order Number) tracking.
167    // When enabled (Some), tracks the 16-bit DONL value to include in RTP packets.
168    // DONL is used when sprop-max-don-diff > 0 (RFC 7798 §7.1).
169    // https://datatracker.ietf.org/doc/html/rfc7798#section-7.1
170    donl: Option<u16>,
171}
172
173impl Default for H265Packetizer {
174    fn default() -> Self {
175        Self {
176            vps_nalu: None,
177            sps_nalu: None,
178            pps_nalu: None,
179            // Pre-allocate to avoid reallocations during hot path
180            pkt_buf: Vec::with_capacity(MAX_PACKET_SIZE),
181            donl: None,
182        }
183    }
184}
185
186impl H265Packetizer {
187    /// with_donl enables or disables DONL (Decoding Order Number) fields in RTP packets.
188    /// DONL should be enabled when `sprop-max-don-diff` > 0 in the SDP (RFC 7798 §7.1).
189    /// When enabled, DONL fields are included in Single NAL, FU, and AP packets.
190    pub fn with_donl(&mut self, value: bool) {
191        self.donl = if value { Some(0) } else { None };
192    }
193
194    /// Increments the DONL counter with wrapping at 65536 (RFC 7798 §7.1).
195    fn increment_donl(&mut self) {
196        if let Some(ref mut donl) = self.donl {
197            *donl = donl.wrapping_add(1);
198        }
199    }
200
201    /// Increments the DONL counter by `n` with wrapping at 65536 (RFC 7798 §7.1).
202    /// Used when emitting an AP containing multiple NAL units, each consuming one DON value.
203    fn increment_donl_by(&mut self, n: u16) {
204        if let Some(ref mut donl) = self.donl {
205            *donl = donl.wrapping_add(n);
206        }
207    }
208
209    /// Builds an Aggregation Packet (AP) from multiple NAL units into a reusable buffer.
210    ///
211    /// # Arguments
212    /// * `template_nalu` - A NAL unit to copy F, layer_id, and tid from.
213    /// * `nal_units` - Slice of NAL units to aggregate.
214    /// * `donl` - Optional DONL value for the first aggregation unit.
215    /// * `buf` - Reusable buffer to write the AP packet into (will be cleared).
216    /// * `max_size` - Maximum buffer size (MTU constraint).
217    ///
218    /// # Returns
219    /// `true` if AP was built successfully, `false` if it exceeded max_size.
220    fn build_ap_packet(
221        template_nalu: &[u8],
222        nal_units: &[&[u8]],
223        donl: Option<u16>,
224        buf: &mut Vec<u8>,
225        max_size: usize,
226    ) -> bool {
227        buf.clear();
228
229        // Build AP header (PayloadHdr) by copying F, layer_id, tid from template
230        // but setting Type=48.
231        const TYPE_MASK: u16 = 0b0111111 << 9;
232        let orig_u16 = u16::from_be_bytes([template_nalu[0], template_nalu[1]]);
233        let ap_u16 = (orig_u16 & !TYPE_MASK) | ((H265NALU_AGGREGATION_PACKET_TYPE as u16) << 9);
234        let ap_hdr = ap_u16.to_be_bytes();
235
236        buf.extend_from_slice(&ap_hdr);
237
238        // Write DONL for first aggregation unit if present (RFC 7798 §4.4.2)
239        if let Some(donl_value) = donl {
240            buf.extend_from_slice(&donl_value.to_be_bytes());
241        }
242
243        // Append each NAL unit with its 16-bit size prefix.
244        // For 2nd and subsequent units, write DOND (1 byte) when DONL is enabled.
245        for (i, nal_unit) in nal_units.iter().enumerate() {
246            // Write DOND (Decoding Order Number Difference) for 2nd+ units.
247            // DOND is always 0 in our case since we emit in order.
248            if donl.is_some() && i > 0 {
249                buf.push(0);
250            }
251            buf.extend_from_slice(&(nal_unit.len() as u16).to_be_bytes());
252            buf.extend_from_slice(nal_unit);
253
254            // Check if we exceeded max size
255            if buf.len() > max_size {
256                return false;
257            }
258        }
259
260        true
261    }
262
263    /// Builds a PACI Packet (Type 50) wrapping an inner NAL unit with optional PHES into a reusable buffer.
264    ///
265    /// PACI packets allow wrapping another NAL unit with additional header information,
266    /// useful for temporal scalability and other extensions.
267    ///
268    /// # Arguments
269    /// * `inner_nalu` - The NAL unit to wrap (complete with 2-byte header)
270    /// * `phes` - Optional Payload Header Extension Structure (PHES) bytes
271    /// * `buf` - Reusable buffer to write the PACI packet into (will be cleared)
272    ///
273    /// # Returns
274    /// `Ok(())` if packet was built successfully, `Err(PacketError)` if PHES is too large (>31 bytes)
275    ///
276    /// Reference: RFC 7798 §4.4.4
277    fn build_paci_packet(
278        inner_nalu: &[u8],
279        phes: &[u8],
280        buf: &mut Vec<u8>,
281    ) -> Result<(), PacketError> {
282        if phes.len() > H265PACI_MAX_PHES_SIZE {
283            return Err(PacketError::ErrH265PACIPHESTooLong);
284        }
285
286        buf.clear();
287
288        // Extract F, layer_id, tid from inner NALU header
289        let inner_header = H265NALUHeader::new(inner_nalu[0], inner_nalu[1]);
290        let inner_type = inner_header.nalu_type();
291
292        // Build PACI PayloadHdr (Type=50)
293        let paci_payload_header = H265NALUHeader::new_with_type(
294            H265NALU_PACI_PACKET_TYPE,
295            inner_header.layer_id(),
296            inner_header.tid(),
297        );
298        let paci_hdr = paci_payload_header.0.to_be_bytes();
299        buf.extend_from_slice(&paci_hdr);
300
301        // Build PACI header fields: A | cType | phssize | F0 F1 F2 | Y
302        // A = F bit from inner NALU
303        let a = if inner_header.f() { 1u16 << 15 } else { 0 };
304        // cType = Type field from inner NALU
305        let ctype = (inner_type as u16) << 9;
306        // phssize = size of PHES (0-31)
307        let phssize = (phes.len() as u16) << 4;
308        // F0 = 1 if PHES contains TSCI (phes.len() >= 3)
309        let f0 = if phes.len() >= 3 { 1u16 << 3 } else { 0 };
310        // F1, F2, Y reserved (must be 0)
311        let paci_fields = a | ctype | phssize | f0;
312        buf.extend_from_slice(&paci_fields.to_be_bytes());
313
314        // Append PHES if present
315        if !phes.is_empty() {
316            buf.extend_from_slice(phes);
317        }
318
319        // Append inner NAL unit payload (without its 2-byte header)
320        if inner_nalu.len() > H265NALU_HEADER_SIZE {
321            buf.extend_from_slice(&inner_nalu[H265NALU_HEADER_SIZE..]);
322        }
323
324        Ok(())
325    }
326
327    /// Finds the next Annex-B NAL unit start code in `payload`, starting at `start`.
328    ///
329    /// Detects `0x00 00 01` or `0x00 00 00 01` as defined by the HEVC Annex-B
330    /// byte stream format (ITU-T Rec. H.265 | ISO/IEC 23008-2, Annex B),
331    /// and returns `(start_index, start_code_len)` (length = 3 or 4).
332    ///
333    /// Returns `(-1, -1)` if no start code is found.
334    fn next_start_code(payload: &[u8], start: usize) -> (isize, isize) {
335        let mut zero_count = 0;
336
337        for (i, &b) in payload[start..].iter().enumerate() {
338            if b == 0 {
339                zero_count += 1;
340                continue;
341            } else if b == 1 && zero_count >= 2 {
342                return ((start + i - zero_count) as isize, (zero_count as isize) + 1);
343            }
344
345            zero_count = 0;
346        }
347
348        (-1, -1)
349    }
350
351    /// Packetization overview (RFC 7798):
352    ///
353    /// Input NAL units (Annex-B or raw)
354    ///     ├─ Single NALU  → RTP payload = NAL header + payload
355    ///     ├─ Large NALU   → Fragmentation Units (Type 49)
356    ///     └─ VPS/SPS/PPS → Aggregation Packet (Type 48)
357    fn emit_nalu(&mut self, nalu: &[u8], mtu: usize, out: &mut Vec<Vec<u8>>) {
358        if mtu == 0 || nalu.len() < H265NALU_HEADER_SIZE {
359            return;
360        }
361
362        // Parse the HEVC NAL unit header.
363        let original_hdr = H265NALUHeader::new(nalu[0], nalu[1]);
364        let original_type = original_hdr.nalu_type();
365
366        // Ignore AUD.
367        if original_type == H265NALU_AUD_NALU_TYPE {
368            return;
369        }
370
371        // Cache parameter sets; send them before the next non-parameter-set NALU.
372        // Option<Vec<u8>> for one-time heap allocation (cold path - happens once per stream).
373        match original_type {
374            H265NALU_VPS_NALU_TYPE => {
375                self.vps_nalu = Some(nalu.to_vec());
376                return;
377            }
378            H265NALU_SPS_NALU_TYPE => {
379                self.sps_nalu = Some(nalu.to_vec());
380                return;
381            }
382            H265NALU_PPS_NALU_TYPE => {
383                self.pps_nalu = Some(nalu.to_vec());
384                return;
385            }
386            _ => {}
387        }
388
389        // If we have cached VPS/SPS/PPS, emit an Aggregation Packet (AP, Type=48)
390        // immediately before the next non-parameter-set NAL unit, per RFC 7798 §4.4.2.
391        if let (Some(sps_nalu), Some(pps_nalu)) = (&self.sps_nalu, &self.pps_nalu) {
392            // Stack-allocate array for NAL unit slices (no heap allocation)
393            let mut nal_units_arr: [&[u8]; 3] = [&[], &[], &[]];
394            let mut count = 0;
395
396            if let Some(vps_nalu) = &self.vps_nalu {
397                nal_units_arr[count] = vps_nalu;
398                count += 1;
399            }
400            nal_units_arr[count] = sps_nalu;
401            count += 1;
402            nal_units_arr[count] = pps_nalu;
403            count += 1;
404
405            let nal_units = &nal_units_arr[..count];
406
407            // Build the AP packet using reusable buffer.
408            // Returns false if AP exceeds MTU.
409            let ap_built =
410                Self::build_ap_packet(nalu, nal_units, self.donl, &mut self.pkt_buf, mtu);
411
412            if ap_built {
413                // AP fits in MTU, emit it.
414                out.push(self.pkt_buf.clone());
415                // Increment DONL by the number of NAL units in the AP.
416                // Each NAL unit inside the AP consumes its own DON value:
417                //   DONL = N (first), DOND derives N+1 (second), N+2 (third), etc.
418                // So after emitting an AP with `count` NAL units, the next packet's
419                // DON should be N + count. (RFC 7798 §4.4.2)
420                self.increment_donl_by(count as u16);
421            } else {
422                // AP exceeds MTU. Fall back to emitting parameter sets as individual
423                // Single NAL Unit packets (RFC 7798 §4.4.1).
424                let vps = self.vps_nalu.take();
425                let sps = self.sps_nalu.take();
426                let pps = self.pps_nalu.take();
427
428                for nal_unit in [&vps, &sps, &pps].into_iter().flatten() {
429                    if nal_unit.len() <= mtu {
430                        if let Some(ref mut donl_value) = self.donl {
431                            // Single NAL with DONL per RFC 7798 §4.4.1:
432                            // [PayloadHdr(2B)] [DONL(2B)] [NAL_payload_data]
433                            self.pkt_buf.clear();
434                            self.pkt_buf
435                                .extend_from_slice(&nal_unit[..H265NALU_HEADER_SIZE]);
436                            self.pkt_buf.extend_from_slice(&donl_value.to_be_bytes());
437                            self.pkt_buf
438                                .extend_from_slice(&nal_unit[H265NALU_HEADER_SIZE..]);
439                            out.push(self.pkt_buf.clone());
440                            *donl_value = donl_value.wrapping_add(1);
441                        } else {
442                            out.push(nal_unit.clone());
443                        }
444                    }
445                    // If parameter set is larger than MTU, we could fragment it as FU, but in practice
446                    // VPS/SPS/PPS are typically small. Silently dropping oversized parameter sets
447                    // is acceptable as a fallback.
448                }
449            }
450
451            // Clear cache after emitting parameter sets (either as AP or individual packets).
452            // For the AP path, these are still Some; for the fallback path, already taken above.
453            self.vps_nalu = None;
454            self.sps_nalu = None;
455            self.pps_nalu = None;
456        }
457
458        // Single NAL Unit packetization (RFC 7798 §4.4.1).
459        // https://datatracker.ietf.org/doc/html/rfc7798#section-4.4.1
460        if nalu.len() <= mtu {
461            // Write DONL field if enabled (2 bytes after NAL header)
462            if let Some(donl_value) = self.donl {
463                self.pkt_buf.clear();
464                // Write NAL header (2 bytes), DONL (2 bytes), then payload
465                self.pkt_buf
466                    .extend_from_slice(&nalu[..H265NALU_HEADER_SIZE]);
467                self.pkt_buf.extend_from_slice(&donl_value.to_be_bytes());
468                self.pkt_buf
469                    .extend_from_slice(&nalu[H265NALU_HEADER_SIZE..]);
470                out.push(self.pkt_buf.clone());
471                self.increment_donl();
472            } else {
473                out.push(nalu.to_vec());
474            }
475            return;
476        }
477
478        // Fragmentation Unit (FU) packetization (RFC 7798 §4.4.3).
479        // https://datatracker.ietf.org/doc/html/rfc7798#section-4.4.3
480        const FU_OVERHEAD: usize = H265NALU_HEADER_SIZE + H265FRAGMENTATION_UNIT_HEADER_SIZE;
481        if mtu <= FU_OVERHEAD || nalu.len() <= H265NALU_HEADER_SIZE {
482            return;
483        }
484
485        // Build FU indicator (Type=49) from original NAL header
486        const TYPE_MASK: u16 = 0b0111111 << 9; // bits 14..9
487        let orig = u16::from_be_bytes([nalu[0], nalu[1]]);
488        let fu = (orig & !TYPE_MASK) | ((H265NALU_FRAGMENTATION_UNIT_TYPE as u16) << 9);
489        let fu_indicator = fu.to_be_bytes();
490
491        let payload = &nalu[H265NALU_HEADER_SIZE..];
492
493        let donl_overhead = if self.donl.is_some() { 2 } else { 0 };
494        let donl_bytes = self.donl.map(u16::to_be_bytes);
495
496        // Clamp to buffer capacity to avoid overflow
497        let effective_mtu = mtu.min(MAX_PACKET_SIZE);
498
499        // Must have room for FU headers (+ optional DONL) and at least 1 byte of payload
500        if effective_mtu <= FU_OVERHEAD + donl_overhead {
501            return;
502        }
503
504        let first_max = effective_mtu - FU_OVERHEAD - donl_overhead;
505        let max_fragment = effective_mtu - FU_OVERHEAD;
506
507        let mut offset = 0;
508
509        while offset < payload.len() {
510            let first = offset == 0;
511            let remaining = payload.len() - offset;
512
513            let budget = if first { first_max } else { max_fragment };
514            let take = remaining.min(budget);
515            debug_assert!(take > 0);
516
517            let end = offset + take == payload.len();
518            let fu_hdr = H265FragmentationUnitHeader::new(first, end, original_type);
519
520            self.pkt_buf.clear();
521            self.pkt_buf.extend_from_slice(&fu_indicator);
522            self.pkt_buf.push(fu_hdr.0);
523            if first {
524                if let Some(ref b) = donl_bytes {
525                    self.pkt_buf.extend_from_slice(b);
526                }
527            }
528            self.pkt_buf
529                .extend_from_slice(&payload[offset..offset + take]);
530
531            out.push(self.pkt_buf.clone());
532            offset += take;
533        }
534
535        // One DONL per NAL unit (not per fragment)
536        self.increment_donl();
537    }
538}
539
540impl Packetizer for H265Packetizer {
541    fn packetize(&mut self, mtu: usize, payload: &[u8]) -> Result<Vec<Vec<u8>>, PacketError> {
542        if payload.is_empty() {
543            return Ok(vec![]);
544        }
545
546        // Validate and log MTU issues.
547        let mtu = match mtu {
548            0 => {
549                warn!("MTU is 0, cannot packetize H.265 - this indicates a programming bug");
550                return Ok(vec![]);
551            }
552            mtu if mtu > MAX_PACKET_SIZE => {
553                warn!(
554                    "MTU {} exceeds MAX_PACKET_SIZE {}, clamping to {}",
555                    mtu, MAX_PACKET_SIZE, MAX_PACKET_SIZE
556                );
557                MAX_PACKET_SIZE
558            }
559            mtu if mtu < MIN_MTU => {
560                warn!(
561                    "MTU {} too small for H.265 fragmentation (min {}) - cannot fragment",
562                    mtu, MIN_MTU
563                );
564                return Ok(vec![]);
565            }
566            mtu => mtu, // Valid MTU, use as-is
567        };
568
569        // Pre-allocate with estimated capacity to avoid reallocations.
570        // Estimate: payload_size / (mtu - overhead) + extra for parameter sets.
571        let estimated_packets = payload
572            .len()
573            .checked_div(mtu.saturating_sub(3))
574            .unwrap_or(1)
575            .saturating_add(4);
576        let mut packets = Vec::with_capacity(estimated_packets);
577
578        // If no Annex-B start codes are present, treat as a single NAL unit.
579        let (mut next_start, mut next_len) = Self::next_start_code(payload, 0);
580        if next_start == -1 {
581            self.emit_nalu(payload, mtu, &mut packets);
582            return Ok(packets);
583        }
584
585        // Walk Annex-B bytestream and emit NAL units between start codes.
586        while next_start != -1 {
587            let nalu_start = (next_start + next_len) as usize;
588            let (next_start2, next_len2) = Self::next_start_code(payload, nalu_start);
589            next_start = next_start2;
590            next_len = next_len2;
591
592            if next_start != -1 {
593                let nalu_end = next_start as usize;
594                self.emit_nalu(&payload[nalu_start..nalu_end], mtu, &mut packets);
595            } else {
596                self.emit_nalu(&payload[nalu_start..], mtu, &mut packets);
597            }
598        }
599
600        Ok(packets)
601    }
602
603    fn is_marker(&mut self, _data: &[u8], _previous: Option<&[u8]>, last: bool) -> bool {
604        last
605    }
606}
607
608/// H265NALUHeader is a H265 NAL Unit Header
609/// https://datatracker.ietf.org/doc/html/rfc7798#section-1.1.4
610///
611/// ```text
612/// +---------------+---------------+
613///  |0|1|2|3|4|5|6|7|0|1|2|3|4|5|6|7|
614///  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
615///  |F|   Type    |  layer_id  | tid |
616///  +-------------+-----------------+
617/// ```
618#[derive(Default, Debug, Copy, Clone, PartialEq, Eq)]
619pub struct H265NALUHeader(pub u16);
620
621impl H265NALUHeader {
622    fn new(high_byte: u8, low_byte: u8) -> Self {
623        H265NALUHeader(((high_byte as u16) << 8) | low_byte as u16)
624    }
625
626    /// f is the forbidden bit, should always be 0.
627    pub fn f(&self) -> bool {
628        (self.0 >> 15) != 0
629    }
630
631    /// nalu_type of NAL Unit.
632    pub fn nalu_type(&self) -> u8 {
633        // 01111110 00000000
634        const MASK: u16 = 0b01111110 << 8;
635        ((self.0 & MASK) >> (8 + 1)) as u8
636    }
637
638    /// is_type_vcl_unit returns whether or not the NAL Unit type is a VCL NAL unit.
639    pub fn is_type_vcl_unit(&self) -> bool {
640        // Type is coded on 6 bits
641        const MSB_MASK: u8 = 0b00100000;
642        (self.nalu_type() & MSB_MASK) == 0
643    }
644
645    /// layer_id should always be 0 in non-3D HEVC context.
646    pub fn layer_id(&self) -> u8 {
647        // 00000001 11111000
648        const MASK: u16 = (0b00000001 << 8) | 0b11111000;
649        ((self.0 & MASK) >> 3) as u8
650    }
651
652    /// tid is the temporal identifier of the NAL unit +1.
653    pub fn tid(&self) -> u8 {
654        const MASK: u16 = 0b00000111;
655        (self.0 & MASK) as u8
656    }
657
658    /// Creates a new H265NALUHeader with specified type, layer_id, and tid.
659    /// Used for building PACI packet headers.
660    pub fn new_with_type(nalu_type: u8, layer_id: u8, tid: u8) -> Self {
661        let header = ((nalu_type as u16) << 9) | ((layer_id as u16) << 3) | (tid as u16);
662        H265NALUHeader(header)
663    }
664
665    /// is_aggregation_packet returns whether or not the packet is an Aggregation packet.
666    pub fn is_aggregation_packet(&self) -> bool {
667        self.nalu_type() == H265NALU_AGGREGATION_PACKET_TYPE
668    }
669
670    /// is_fragmentation_unit returns whether or not the packet is a Fragmentation Unit packet.
671    pub fn is_fragmentation_unit(&self) -> bool {
672        self.nalu_type() == H265NALU_FRAGMENTATION_UNIT_TYPE
673    }
674
675    /// is_paci_packet returns whether or not the packet is a PACI packet.
676    pub fn is_paci_packet(&self) -> bool {
677        self.nalu_type() == H265NALU_PACI_PACKET_TYPE
678    }
679
680    /// is_idr_picture returns whether or not the NAL unit is an IDR picture.
681    pub fn is_idr_picture(&self) -> bool {
682        let typ = self.nalu_type();
683        typ == H265NALU_IDR_W_RADL || typ == H265NALU_IDR_N_LP
684    }
685
686    /// is_irap returns whether or not the NAL unit is an IRAP (Intra Random Access Point) picture.
687    /// IRAP pictures include BLA, IDR, and CRA pictures, which are all random access points / keyframes.
688    pub fn is_irap(&self) -> bool {
689        let typ = self.nalu_type();
690        matches!(
691            typ,
692            H265NALU_BLA_W_LP
693                | H265NALU_BLA_W_RADL
694                | H265NALU_BLA_N_LP
695                | H265NALU_IDR_W_RADL
696                | H265NALU_IDR_N_LP
697                | H265NALU_CRA_NUT
698        )
699    }
700}
701
702///
703/// Single NAL Unit Packet implementation
704///
705/// H265SingleNALUnitPacket represents a NALU packet, containing exactly one NAL unit.
706///
707/// ```text
708///     0                   1                   2                   3
709///    0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
710///   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
711///   |           PayloadHdr          |      DONL (conditional)       |
712///   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
713///   |                                                               |
714///   |                  NAL unit payload data                        |
715///   |                                                               |
716///   |                               +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
717///   |                               :...OPTIONAL RTP padding        |
718///   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
719/// ```
720///
721/// Reference: https://datatracker.ietf.org/doc/html/rfc7798#section-4.4.1
722#[derive(Default, Debug, Clone, PartialEq, Eq)]
723pub struct H265SingleNALUnitPacket {
724    /// payload_header is the header of the H265 packet.
725    payload_header: H265NALUHeader,
726    /// donl is a 16-bit field, that may or may not be present.
727    donl: Option<u16>,
728    /// payload of the fragmentation unit.
729    payload: Vec<u8>,
730
731    might_need_donl: bool,
732}
733
734impl H265SingleNALUnitPacket {
735    /// with_donl can be called to specify whether or not DONL might be parsed.
736    /// DONL may need to be parsed if `sprop-max-don-diff` is greater than 0 on the RTP stream.
737    pub fn with_donl(&mut self, value: bool) {
738        self.might_need_donl = value;
739    }
740
741    /// depacketize parses the passed byte slice and stores the result in the
742    /// H265SingleNALUnitPacket this method is called upon.
743    fn depacketize(&mut self, payload: &[u8]) -> Result<(), PacketError> {
744        if payload.len() <= H265NALU_HEADER_SIZE {
745            return Err(PacketError::ErrShortPacket);
746        }
747
748        let payload_header = H265NALUHeader::new(payload[0], payload[1]);
749        if payload_header.f() {
750            return Err(PacketError::ErrH265CorruptedPacket);
751        }
752        if payload_header.is_fragmentation_unit()
753            || payload_header.is_paci_packet()
754            || payload_header.is_aggregation_packet()
755        {
756            return Err(PacketError::ErrInvalidH265PacketType);
757        }
758
759        let mut payload = &payload[2..];
760
761        if self.might_need_donl {
762            // sizeof(uint16)
763            if payload.len() <= 2 {
764                return Err(PacketError::ErrShortPacket);
765            }
766
767            let donl = ((payload[0] as u16) << 8) | (payload[1] as u16);
768            self.donl = Some(donl);
769            payload = &payload[2..];
770        }
771
772        self.payload_header = payload_header;
773        self.payload = payload.to_vec();
774
775        Ok(())
776    }
777
778    /// payload_header returns the NALU header of the packet.
779    pub fn payload_header(&self) -> H265NALUHeader {
780        self.payload_header
781    }
782
783    /// donl returns the DONL of the packet.
784    pub fn donl(&self) -> Option<u16> {
785        self.donl
786    }
787
788    /// payload returns the Fragmentation Unit packet payload.
789    pub fn payload(&self) -> &[u8] {
790        &self.payload
791    }
792}
793
794///
795/// Aggregation Packets implementation
796///
797/// H265AggregationUnitFirst represent the First Aggregation Unit in an AP.
798///
799/// ```text
800///    0                   1                   2                   3
801///    0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
802///   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
803///                   :       DONL (conditional)      |   NALU size   |
804///   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
805///   |   NALU size   |                                               |
806///   +-+-+-+-+-+-+-+-+         NAL unit                              |
807///   |                                                               |
808///   |                               +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
809///   |                               :
810///   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
811/// ```
812///
813/// Reference: https://datatracker.ietf.org/doc/html/rfc7798#section-4.4.2
814#[derive(Default, Debug, Clone, PartialEq, Eq)]
815pub struct H265AggregationUnitFirst {
816    donl: Option<u16>,
817    nal_unit_size: u16,
818    nal_unit: Vec<u8>,
819}
820
821impl H265AggregationUnitFirst {
822    /// donl field, when present, specifies the value of the 16 least
823    /// significant bits of the decoding order number of the aggregated NAL
824    /// unit.
825    pub fn donl(&self) -> Option<u16> {
826        self.donl
827    }
828
829    /// nalu_size represents the size, in bytes, of the nal_unit.
830    pub fn nalu_size(&self) -> u16 {
831        self.nal_unit_size
832    }
833
834    /// nal_unit payload.
835    pub fn nal_unit(&self) -> &[u8] {
836        &self.nal_unit
837    }
838}
839
840/// H265AggregationUnit represent the an Aggregation Unit in an AP, which is not the first one.
841///
842///    0                   1                   2                   3
843///    0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
844///   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
845///                   : DOND (cond)   |          NALU size            |
846///   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
847///   |                                                               |
848///   |                       NAL unit                                |
849///   |                               +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
850///   |                               :
851///   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
852///
853/// Reference: https://datatracker.ietf.org/doc/html/rfc7798#section-4.4.2
854#[derive(Default, Debug, Clone, PartialEq, Eq)]
855pub struct H265AggregationUnit {
856    dond: Option<u8>,
857    nal_unit_size: u16,
858    nal_unit: Vec<u8>,
859}
860
861impl H265AggregationUnit {
862    /// dond field plus 1 specifies the difference between
863    /// the decoding order number values of the current aggregated NAL unit
864    /// and the preceding aggregated NAL unit in the same AP.
865    pub fn dond(&self) -> Option<u8> {
866        self.dond
867    }
868
869    /// nalu_size represents the size, in bytes, of the nal_unit.
870    pub fn nalu_size(&self) -> u16 {
871        self.nal_unit_size
872    }
873
874    /// nal_unit payload.
875    pub fn nal_unit(&self) -> &[u8] {
876        &self.nal_unit
877    }
878}
879
880/// H265AggregationPacket represents an Aggregation packet.
881///
882/// ```text
883///   0                   1                   2                   3
884///    0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
885///   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
886///   |    PayloadHdr (Type=48)       |                               |
887///   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+                               |
888///   |                                                               |
889///   |             two or more aggregation units                     |
890///   |                                                               |
891///   |                               +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
892///   |                               :...OPTIONAL RTP padding        |
893///   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
894/// ```
895///
896/// Reference: https://datatracker.ietf.org/doc/html/rfc7798#section-4.4.2
897#[derive(Default, Debug, Clone, PartialEq, Eq)]
898pub struct H265AggregationPacket {
899    first_unit: Option<H265AggregationUnitFirst>,
900    other_units: Vec<H265AggregationUnit>,
901
902    might_need_donl: bool,
903}
904
905impl H265AggregationPacket {
906    /// with_donl can be called to specify whether or not DONL might be parsed.
907    /// DONL may need to be parsed if `sprop-max-don-diff` is greater than 0 on the RTP stream.
908    pub fn with_donl(&mut self, value: bool) {
909        self.might_need_donl = value;
910    }
911
912    /// depacketize parses the passed byte slice and stores the result in the
913    /// H265AggregationPacket this method is called upon.
914    fn depacketize(&mut self, payload: &[u8]) -> Result<(), PacketError> {
915        if payload.len() <= H265NALU_HEADER_SIZE {
916            return Err(PacketError::ErrShortPacket);
917        }
918
919        let payload_header = H265NALUHeader::new(payload[0], payload[1]);
920        if payload_header.f() {
921            return Err(PacketError::ErrH265CorruptedPacket);
922        }
923        if !payload_header.is_aggregation_packet() {
924            return Err(PacketError::ErrInvalidH265PacketType);
925        }
926
927        // First parse the first aggregation unit
928        let mut payload = &payload[2..];
929        let mut first_unit = H265AggregationUnitFirst::default();
930
931        if self.might_need_donl {
932            if payload.len() < 2 {
933                return Err(PacketError::ErrShortPacket);
934            }
935
936            let donl = ((payload[0] as u16) << 8) | (payload[1] as u16);
937            first_unit.donl = Some(donl);
938
939            payload = &payload[2..];
940        }
941        if payload.len() < 2 {
942            return Err(PacketError::ErrShortPacket);
943        }
944        first_unit.nal_unit_size = ((payload[0] as u16) << 8) | (payload[1] as u16);
945        payload = &payload[2..];
946
947        if payload.len() < first_unit.nal_unit_size as usize {
948            return Err(PacketError::ErrShortPacket);
949        }
950
951        first_unit.nal_unit = payload[..first_unit.nal_unit_size as usize].to_vec();
952        payload = &payload[first_unit.nal_unit_size as usize..];
953
954        // Parse remaining Aggregation Units
955        let mut units = vec![]; //H265AggregationUnit
956        loop {
957            let mut unit = H265AggregationUnit::default();
958
959            if self.might_need_donl {
960                if payload.is_empty() {
961                    break;
962                }
963
964                let dond = payload[0];
965                unit.dond = Some(dond);
966
967                payload = &payload[1..];
968            }
969
970            if payload.len() < 2 {
971                break;
972            }
973            unit.nal_unit_size = ((payload[0] as u16) << 8) | (payload[1] as u16);
974            payload = &payload[2..];
975
976            if payload.len() < unit.nal_unit_size as usize {
977                break;
978            }
979
980            unit.nal_unit = payload[..unit.nal_unit_size as usize].to_vec();
981            payload = &payload[unit.nal_unit_size as usize..];
982
983            units.push(unit);
984        }
985
986        // There need to be **at least** two Aggregation Units (first + another one)
987        if units.is_empty() {
988            return Err(PacketError::ErrShortPacket);
989        }
990
991        self.first_unit = Some(first_unit);
992        self.other_units = units;
993
994        Ok(())
995    }
996
997    /// first_unit returns the first Aggregated Unit of the packet.
998    pub fn first_unit(&self) -> Option<&H265AggregationUnitFirst> {
999        self.first_unit.as_ref()
1000    }
1001
1002    /// other_units returns the all the other Aggregated Unit of the packet (excluding the first one).
1003    pub fn other_units(&self) -> &[H265AggregationUnit] {
1004        self.other_units.as_slice()
1005    }
1006
1007    /// nal_units returns all NAL units in the aggregation packet.
1008    pub fn nal_units(&self) -> Vec<&[u8]> {
1009        let mut units = Vec::new();
1010        if let Some(first) = &self.first_unit {
1011            units.push(first.nal_unit.as_slice());
1012        }
1013        for unit in &self.other_units {
1014            units.push(unit.nal_unit.as_slice());
1015        }
1016        units
1017    }
1018}
1019
1020///
1021/// Fragmentation Unit implementation
1022///
1023
1024const H265FRAGMENTATION_UNIT_HEADER_SIZE: usize = 1;
1025
1026/// H265FragmentationUnitHeader is a H265 FU Header
1027///
1028/// ```text
1029/// +---------------+
1030/// |0|1|2|3|4|5|6|7|
1031/// +-+-+-+-+-+-+-+-+
1032/// |S|E|  fu_type   |
1033/// +---------------+
1034/// ```
1035#[derive(Default, Debug, Copy, Clone, PartialEq, Eq)]
1036pub struct H265FragmentationUnitHeader(pub u8);
1037
1038impl H265FragmentationUnitHeader {
1039    /// new creates a new H265FragmentationUnitHeader.
1040    ///
1041    /// # Arguments
1042    /// * `s` - Start bit: true if this is the first fragment
1043    /// * `e` - End bit: true if this is the last fragment
1044    /// * `fu_type` - The NAL unit type of the fragmented NAL unit (6 bits)
1045    pub fn new(s: bool, e: bool, fu_type: u8) -> Self {
1046        let mut header = fu_type & 0b0011_1111; // Mask to 6 bits
1047        if s {
1048            header |= 0b1000_0000; // Set S bit
1049        }
1050        if e {
1051            header |= 0b0100_0000; // Set E bit
1052        }
1053        H265FragmentationUnitHeader(header)
1054    }
1055
1056    /// s represents the start of a fragmented NAL unit.
1057    pub fn s(&self) -> bool {
1058        const MASK: u8 = 0b10000000;
1059        ((self.0 & MASK) >> 7) != 0
1060    }
1061
1062    /// e represents the end of a fragmented NAL unit.
1063    pub fn e(&self) -> bool {
1064        const MASK: u8 = 0b01000000;
1065        ((self.0 & MASK) >> 6) != 0
1066    }
1067
1068    /// fu_type MUST be equal to the field Type of the fragmented NAL unit.
1069    pub fn fu_type(&self) -> u8 {
1070        const MASK: u8 = 0b00111111;
1071        self.0 & MASK
1072    }
1073}
1074
1075/// H265FragmentationUnitPacket represents a single Fragmentation Unit packet.
1076///
1077///  0                   1                   2                   3
1078/// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
1079/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1080/// |    PayloadHdr (Type=49)       |   FU header   | DONL (cond)   |
1081/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-|
1082/// | DONL (cond)   |                                               |
1083/// |-+-+-+-+-+-+-+-+                                               |
1084/// |                         FU payload                            |
1085/// |                                                               |
1086/// |                               +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1087/// |                               :...OPTIONAL RTP padding        |
1088/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1089///
1090/// Reference: https://datatracker.ietf.org/doc/html/rfc7798#section-4.4.3
1091#[derive(Default, Debug, Clone, PartialEq, Eq)]
1092pub struct H265FragmentationUnitPacket {
1093    /// payload_header is the header of the H265 packet.
1094    payload_header: H265NALUHeader,
1095    /// fu_header is the header of the fragmentation unit
1096    fu_header: H265FragmentationUnitHeader,
1097    /// donl is a 16-bit field, that may or may not be present.
1098    donl: Option<u16>,
1099    /// payload of the fragmentation unit.
1100    payload: Vec<u8>,
1101
1102    might_need_donl: bool,
1103}
1104
1105impl H265FragmentationUnitPacket {
1106    /// with_donl can be called to specify whether or not DONL might be parsed.
1107    /// DONL may need to be parsed if `sprop-max-don-diff` is greater than 0 on the RTP stream.
1108    pub fn with_donl(&mut self, value: bool) {
1109        self.might_need_donl = value;
1110    }
1111
1112    /// depacketize parses the passed byte slice and stores the result in the
1113    /// H265FragmentationUnitPacket this method is called upon.
1114    fn depacketize(&mut self, payload: &[u8]) -> Result<(), PacketError> {
1115        const TOTAL_HEADER_SIZE: usize = H265NALU_HEADER_SIZE + H265FRAGMENTATION_UNIT_HEADER_SIZE;
1116        if payload.len() <= TOTAL_HEADER_SIZE {
1117            return Err(PacketError::ErrShortPacket);
1118        }
1119
1120        let payload_header = H265NALUHeader::new(payload[0], payload[1]);
1121        if payload_header.f() {
1122            return Err(PacketError::ErrH265CorruptedPacket);
1123        }
1124        if !payload_header.is_fragmentation_unit() {
1125            return Err(PacketError::ErrInvalidH265PacketType);
1126        }
1127
1128        let fu_header = H265FragmentationUnitHeader(payload[2]);
1129        let mut payload = &payload[3..];
1130
1131        if fu_header.s() && self.might_need_donl {
1132            if payload.len() <= 2 {
1133                return Err(PacketError::ErrShortPacket);
1134            }
1135
1136            let donl = ((payload[0] as u16) << 8) | (payload[1] as u16);
1137            self.donl = Some(donl);
1138            payload = &payload[2..];
1139        }
1140
1141        self.payload_header = payload_header;
1142        self.fu_header = fu_header;
1143        self.payload = payload.to_vec();
1144
1145        Ok(())
1146    }
1147
1148    /// payload_header returns the NALU header of the packet.
1149    pub fn payload_header(&self) -> H265NALUHeader {
1150        self.payload_header
1151    }
1152
1153    /// fu_header returns the Fragmentation Unit Header of the packet.
1154    pub fn fu_header(&self) -> H265FragmentationUnitHeader {
1155        self.fu_header
1156    }
1157
1158    /// donl returns the DONL of the packet.
1159    pub fn donl(&self) -> Option<u16> {
1160        self.donl
1161    }
1162
1163    /// payload returns the Fragmentation Unit packet payload.
1164    pub fn payload(&self) -> &[u8] {
1165        &self.payload
1166    }
1167}
1168
1169///
1170/// PACI implementation
1171///
1172
1173/// H265PACIPacket represents a single H265 PACI packet.
1174///
1175/// ```text
1176///  0                   1                   2                   3
1177/// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
1178/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1179/// |    PayloadHdr (Type=50)       |A|   cType   | phssize |F0..2|Y|
1180/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1181/// |        payload Header Extension Structure (phes)              |
1182/// |=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=|
1183/// |                                                               |
1184/// |                  PACI payload: NAL unit                       |
1185/// |                   . . .                                       |
1186/// |                                                               |
1187/// |                               +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1188/// |                               :...OPTIONAL RTP padding        |
1189/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1190/// ```
1191///
1192/// Reference: https://datatracker.ietf.org/doc/html/rfc7798#section-4.4.4
1193#[derive(Default, Debug, Clone, PartialEq, Eq)]
1194pub struct H265PACIPacket {
1195    /// payload_header is the header of the H265 packet.
1196    payload_header: H265NALUHeader,
1197
1198    /// Field which holds value for `A`, `cType`, `phssize`, `F0`, `F1`, `F2` and `Y` fields.
1199    paci_header_fields: u16,
1200
1201    /// phes is a header extension, of byte length `phssize`
1202    phes: Vec<u8>,
1203
1204    /// payload contains NAL units & optional padding
1205    payload: Vec<u8>,
1206}
1207
1208impl H265PACIPacket {
1209    /// payload_header returns the NAL Unit Header.
1210    pub fn payload_header(&self) -> H265NALUHeader {
1211        self.payload_header
1212    }
1213
1214    /// a copies the F bit of the PACI payload NALU.
1215    pub fn a(&self) -> bool {
1216        const MASK: u16 = 0b10000000 << 8;
1217        (self.paci_header_fields & MASK) != 0
1218    }
1219
1220    /// ctype copies the Type field of the PACI payload NALU.
1221    pub fn ctype(&self) -> u8 {
1222        const MASK: u16 = 0b01111110 << 8;
1223        ((self.paci_header_fields & MASK) >> (8 + 1)) as u8
1224    }
1225
1226    /// phs_size indicates the size of the phes field.
1227    pub fn phs_size(&self) -> u8 {
1228        const MASK: u16 = (0b00000001 << 8) | 0b11110000;
1229        ((self.paci_header_fields & MASK) >> 4) as u8
1230    }
1231
1232    /// f0 indicates the presence of a Temporal Scalability support extension in the phes.
1233    pub fn f0(&self) -> bool {
1234        const MASK: u16 = 0b00001000;
1235        (self.paci_header_fields & MASK) != 0
1236    }
1237
1238    /// f1 must be zero, reserved for future extensions.
1239    pub fn f1(&self) -> bool {
1240        const MASK: u16 = 0b00000100;
1241        (self.paci_header_fields & MASK) != 0
1242    }
1243
1244    /// f2 must be zero, reserved for future extensions.
1245    pub fn f2(&self) -> bool {
1246        const MASK: u16 = 0b00000010;
1247        (self.paci_header_fields & MASK) != 0
1248    }
1249
1250    /// y must be zero, reserved for future extensions.
1251    pub fn y(&self) -> bool {
1252        const MASK: u16 = 0b00000001;
1253        (self.paci_header_fields & MASK) != 0
1254    }
1255
1256    /// phes contains header extensions. Its size is indicated by phssize.
1257    pub fn phes(&self) -> &[u8] {
1258        &self.phes
1259    }
1260
1261    /// payload is a single NALU or NALU-like struct, not including the first two octets (header).
1262    pub fn payload(&self) -> &[u8] {
1263        &self.payload
1264    }
1265
1266    /// tsci returns the Temporal Scalability Control Information extension, if present.
1267    pub fn tsci(&self) -> Option<H265TSCI> {
1268        if !self.f0() || self.phs_size() < 3 {
1269            return None;
1270        }
1271
1272        Some(H265TSCI(
1273            ((self.phes[0] as u32) << 16) | ((self.phes[1] as u32) << 8) | self.phes[0] as u32,
1274        ))
1275    }
1276
1277    /// depacketize parses the passed byte slice and stores the result in the
1278    /// H265PACIPacket this method is called upon.
1279    fn depacketize(&mut self, payload: &[u8]) -> Result<(), PacketError> {
1280        const TOTAL_HEADER_SIZE: usize = H265NALU_HEADER_SIZE + 2;
1281        if payload.len() <= TOTAL_HEADER_SIZE {
1282            return Err(PacketError::ErrShortPacket);
1283        }
1284
1285        let payload_header = H265NALUHeader::new(payload[0], payload[1]);
1286        if payload_header.f() {
1287            return Err(PacketError::ErrH265CorruptedPacket);
1288        }
1289        if !payload_header.is_paci_packet() {
1290            return Err(PacketError::ErrInvalidH265PacketType);
1291        }
1292
1293        let paci_header_fields = ((payload[2] as u16) << 8) | (payload[3] as u16);
1294        let mut payload = &payload[4..];
1295
1296        self.paci_header_fields = paci_header_fields;
1297        let header_extension_size = self.phs_size();
1298
1299        if payload.len() < header_extension_size as usize + 1 {
1300            self.paci_header_fields = 0;
1301            return Err(PacketError::ErrShortPacket);
1302        }
1303
1304        self.payload_header = payload_header;
1305
1306        if header_extension_size > 0 {
1307            self.phes = payload[..header_extension_size as usize].to_vec();
1308        }
1309
1310        payload = &payload[header_extension_size as usize..];
1311        self.payload = payload.to_vec();
1312
1313        Ok(())
1314    }
1315
1316    /// Packetizes a PACI packet by wrapping an inner NAL unit with optional PHES.
1317    ///
1318    /// Uses the packetizer's reusable buffer for zero-allocation hot path.
1319    ///
1320    /// # Arguments
1321    /// * `inner_nalu` - The NAL unit to wrap (complete with 2-byte header)
1322    /// * `phes` - Optional Payload Header Extension Structure (PHES) bytes
1323    /// * `buf` - Reusable buffer to write the packet (will be cleared)
1324    ///
1325    /// # Returns
1326    /// Serialized PACI packet bytes, or error if PHES is too large
1327    pub fn packetize(
1328        inner_nalu: &[u8],
1329        phes: &[u8],
1330        buf: &mut Vec<u8>,
1331    ) -> Result<Vec<u8>, PacketError> {
1332        H265Packetizer::build_paci_packet(inner_nalu, phes, buf)?;
1333        Ok(buf.clone())
1334    }
1335}
1336
1337///
1338/// Temporal Scalability Control Information
1339///
1340
1341/// H265TSCI is a Temporal Scalability Control Information header extension.
1342/// Reference: https://datatracker.ietf.org/doc/html/rfc7798#section-4.5
1343#[derive(Default, Debug, Copy, Clone, PartialEq, Eq)]
1344pub struct H265TSCI(pub u32);
1345
1346impl H265TSCI {
1347    /// tl0picidx see RFC7798 for more details.
1348    pub fn tl0picidx(&self) -> u8 {
1349        const M1: u32 = 0xFFFF0000;
1350        const M2: u32 = 0xFF00;
1351        ((((self.0 & M1) >> 16) & M2) >> 8) as u8
1352    }
1353
1354    /// irap_pic_id see RFC7798 for more details.
1355    pub fn irap_pic_id(&self) -> u8 {
1356        const M1: u32 = 0xFFFF0000;
1357        const M2: u32 = 0x00FF;
1358        (((self.0 & M1) >> 16) & M2) as u8
1359    }
1360
1361    /// s see RFC7798 for more details.
1362    pub fn s(&self) -> bool {
1363        const M1: u32 = 0xFF00;
1364        const M2: u32 = 0b10000000;
1365        (((self.0 & M1) >> 8) & M2) != 0
1366    }
1367
1368    /// e see RFC7798 for more details.
1369    pub fn e(&self) -> bool {
1370        const M1: u32 = 0xFF00;
1371        const M2: u32 = 0b01000000;
1372        (((self.0 & M1) >> 8) & M2) != 0
1373    }
1374
1375    /// res see RFC7798 for more details.
1376    pub fn res(&self) -> u8 {
1377        const M1: u32 = 0xFF00;
1378        const M2: u32 = 0b00111111;
1379        (((self.0 & M1) >> 8) & M2) as u8
1380    }
1381}
1382
1383///
1384/// H265 Payload Enum
1385///
1386#[derive(Debug, Clone, PartialEq, Eq)]
1387pub enum H265Payload {
1388    H265SingleNALUnitPacket(H265SingleNALUnitPacket),
1389    H265FragmentationUnitPacket(H265FragmentationUnitPacket),
1390    H265AggregationPacket(H265AggregationPacket),
1391    H265PACIPacket(H265PACIPacket),
1392}
1393
1394impl Default for H265Payload {
1395    fn default() -> Self {
1396        H265Payload::H265SingleNALUnitPacket(H265SingleNALUnitPacket::default())
1397    }
1398}
1399
1400/// Depacketizes H265 RTP packets.
1401#[derive(Default, Debug, Clone, PartialEq, Eq)]
1402pub struct H265Depacketizer {
1403    payload: H265Payload,
1404    might_need_donl: bool,
1405    fu_buffer: Option<Vec<u8>>,
1406}
1407
1408impl H265Depacketizer {
1409    /// with_donl can be called to specify whether or not DONL might be parsed.
1410    /// DONL may need to be parsed if `sprop-max-don-diff` is greater than 0 on the RTP stream.
1411    pub fn with_donl(&mut self, value: bool) {
1412        self.might_need_donl = value;
1413    }
1414
1415    /// payload returns the populated payload.
1416    /// Must be casted to one of:
1417    /// - H265SingleNALUnitPacket
1418    /// - H265FragmentationUnitPacket
1419    /// - H265AggregationPacket
1420    /// - H265PACIPacket
1421    pub fn payload(&self) -> &H265Payload {
1422        &self.payload
1423    }
1424}
1425
1426impl Depacketizer for H265Depacketizer {
1427    fn out_size_hint(&self, packets_size: usize) -> Option<usize> {
1428        // Roughly account for Annex B start codes
1429        let estimated_packets = (packets_size / 1200).saturating_add(1);
1430        Some(packets_size.saturating_add(4usize.saturating_mul(estimated_packets)))
1431    }
1432
1433    /// depacketize parses the passed byte slice and stores the result
1434    /// in the H265Packet this method is called upon
1435    fn depacketize(
1436        &mut self,
1437        packet: &[u8],
1438        out: &mut Vec<u8>,
1439        codec_extra: &mut CodecExtra,
1440    ) -> Result<(), PacketError> {
1441        if packet.len() <= H265NALU_HEADER_SIZE {
1442            return Err(PacketError::ErrShortPacket);
1443        }
1444
1445        let header = H265NALUHeader::new(packet[0], packet[1]);
1446        if header.f() {
1447            return Err(PacketError::ErrH265CorruptedPacket);
1448        }
1449
1450        if header.is_paci_packet() {
1451            let mut decoded = H265PACIPacket::default();
1452            decoded.depacketize(packet)?;
1453
1454            // Emit PACI payload with Annex-B start code
1455            out.extend_from_slice(ANNEXB_NALUSTART_CODE);
1456            out.extend_from_slice(&decoded.payload());
1457
1458            // Check if this is a keyframe.
1459            if decoded.payload().len() >= H265NALU_HEADER_SIZE {
1460                let payload_hdr = H265NALUHeader::new(decoded.payload()[0], decoded.payload()[1]);
1461                let is_keyframe = if let CodecExtra::H265(e) = codec_extra {
1462                    payload_hdr.is_irap() | e.is_keyframe
1463                } else {
1464                    payload_hdr.is_irap()
1465                };
1466                *codec_extra = CodecExtra::H265(H265CodecExtra { is_keyframe });
1467            }
1468
1469            self.payload = H265Payload::H265PACIPacket(decoded);
1470        } else if header.is_fragmentation_unit() {
1471            let mut decoded = H265FragmentationUnitPacket::default();
1472            decoded.with_donl(self.might_need_donl);
1473
1474            decoded.depacketize(packet)?;
1475
1476            let fu_header = decoded.fu_header();
1477
1478            if fu_header.s() {
1479                // Start of fragmented NAL unit.
1480                // Reuse existing buffer to avoid allocation on every FU start.
1481                match &mut self.fu_buffer {
1482                    Some(buf) => buf.clear(),
1483                    None => {
1484                        // First FU ever - allocate with typical max NAL size.
1485                        // 128KB covers most 4K frames.
1486                        self.fu_buffer = Some(Vec::with_capacity(128 * 1024));
1487                    }
1488                }
1489            }
1490
1491            if let Some(ref mut buf) = self.fu_buffer {
1492                buf.extend_from_slice(&decoded.payload());
1493            }
1494
1495            if fu_header.e() {
1496                // End of fragmented NAL unit - reconstruct original NAL.
1497                // Borrow buffer instead of take() to preserve allocation for reuse.
1498                if let Some(ref fu_payload) = self.fu_buffer {
1499                    // Rebuild original NAL unit header from FU header.
1500                    const TYPE_MASK: u16 = 0b0111111 << 9; // bits 14..9
1501                    let payload_hdr_u16 = u16::from_be_bytes([packet[0], packet[1]]);
1502                    let orig_type = fu_header.fu_type();
1503                    let orig_hdr_u16 = (payload_hdr_u16 & !TYPE_MASK) | ((orig_type as u16) << 9);
1504                    let orig_hdr = orig_hdr_u16.to_be_bytes();
1505                    let orig_hdr_obj = H265NALUHeader::new(orig_hdr[0], orig_hdr[1]);
1506
1507                    // Check if this is a keyframe.
1508                    let is_keyframe = if let CodecExtra::H265(e) = codec_extra {
1509                        orig_hdr_obj.is_irap() | e.is_keyframe
1510                    } else {
1511                        orig_hdr_obj.is_irap()
1512                    };
1513                    *codec_extra = CodecExtra::H265(H265CodecExtra { is_keyframe });
1514
1515                    // Emit Annex-B start code + original NAL header + payload.
1516                    out.extend_from_slice(ANNEXB_NALUSTART_CODE);
1517                    out.extend_from_slice(&orig_hdr);
1518                    out.extend_from_slice(fu_payload);
1519                }
1520                // Note: We don't clear fu_buffer here - it will be cleared on next FU start.
1521                // This preserves the allocation for reuse.
1522            }
1523
1524            self.payload = H265Payload::H265FragmentationUnitPacket(decoded);
1525        } else if header.is_aggregation_packet() {
1526            // Optimized AP parsing: write directly to output like H264 does.
1527            // Parse inline without intermediate Vec allocations.
1528
1529            let mut offset = H265NALU_HEADER_SIZE;
1530            let mut is_first_unit = true;
1531            let mut unit_count = 0;
1532
1533            // Parse and emit NAL units in one pass (zero-copy approach)
1534            while offset < packet.len() {
1535                // Skip DONL/DOND if present
1536                if self.might_need_donl {
1537                    if is_first_unit {
1538                        // First unit has DONL (2 bytes)
1539                        if offset + 2 > packet.len() {
1540                            break;
1541                        }
1542                        offset += 2;
1543                    } else {
1544                        // Subsequent units have DOND (1 byte)
1545                        if offset + 1 > packet.len() {
1546                            break;
1547                        }
1548                        offset += 1;
1549                    }
1550                }
1551
1552                // Read NAL unit size (2 bytes)
1553                if offset + 2 > packet.len() {
1554                    break;
1555                }
1556                let nalu_size = ((packet[offset] as usize) << 8) | (packet[offset + 1] as usize);
1557                offset += 2;
1558
1559                // Validate NAL unit fits in packet
1560                if offset + nalu_size > packet.len() {
1561                    break;
1562                }
1563
1564                let nalu = &packet[offset..offset + nalu_size];
1565                offset += nalu_size;
1566                unit_count += 1;
1567
1568                // Check if keyframe
1569                if nalu.len() >= H265NALU_HEADER_SIZE {
1570                    let nalu_hdr = H265NALUHeader::new(nalu[0], nalu[1]);
1571                    let is_keyframe = if let CodecExtra::H265(e) = codec_extra {
1572                        nalu_hdr.is_irap() | e.is_keyframe
1573                    } else {
1574                        nalu_hdr.is_irap()
1575                    };
1576                    *codec_extra = CodecExtra::H265(H265CodecExtra { is_keyframe });
1577                }
1578
1579                // Write to output (zero allocation)
1580                out.extend_from_slice(ANNEXB_NALUSTART_CODE);
1581                out.extend_from_slice(nalu);
1582
1583                is_first_unit = false;
1584            }
1585
1586            // AP must have at least 2 units (RFC 7798)
1587            if unit_count < 2 {
1588                return Err(PacketError::ErrShortPacket);
1589            }
1590
1591            // Still parse into struct for payload() API compatibility.
1592            // This allocates but is needed for the public API.
1593            let mut decoded = H265AggregationPacket::default();
1594            decoded.with_donl(self.might_need_donl);
1595            decoded.depacketize(packet)?; // Validate structure
1596
1597            self.payload = H265Payload::H265AggregationPacket(decoded);
1598        } else {
1599            // Single NAL unit packet.
1600            let mut decoded = H265SingleNALUnitPacket::default();
1601            decoded.with_donl(self.might_need_donl);
1602
1603            decoded.depacketize(packet)?;
1604
1605            // Check if this is a keyframe.
1606            let is_keyframe = if let CodecExtra::H265(e) = codec_extra {
1607                header.is_irap() | e.is_keyframe
1608            } else {
1609                header.is_irap()
1610            };
1611            *codec_extra = CodecExtra::H265(H265CodecExtra { is_keyframe });
1612
1613            // Emit Annex-B start code + NAL header + payload (without DONL).
1614            out.extend_from_slice(ANNEXB_NALUSTART_CODE);
1615            let hdr = decoded.payload_header();
1616            out.extend_from_slice(&[(hdr.0 >> 8) as u8, (hdr.0 & 0xFF) as u8]);
1617            out.extend_from_slice(&decoded.payload());
1618
1619            self.payload = H265Payload::H265SingleNALUnitPacket(decoded);
1620        }
1621
1622        Ok(())
1623    }
1624
1625    /// is_partition_head checks if this is the head of a packetized nalu stream.
1626    fn is_partition_head(&self, payload: &[u8]) -> bool {
1627        if payload.len() < H265NALU_HEADER_SIZE {
1628            return false;
1629        }
1630
1631        let header = H265NALUHeader::new(payload[0], payload[1]);
1632
1633        // If F bit is set, this is always a partition head (error case, but treated as head)
1634        if header.f() {
1635            return true;
1636        }
1637
1638        // Single NAL unit packets are always partition heads
1639        if !header.is_fragmentation_unit()
1640            && !header.is_aggregation_packet()
1641            && !header.is_paci_packet()
1642        {
1643            return true;
1644        }
1645
1646        // Aggregation packets are partition heads
1647        if header.is_aggregation_packet() {
1648            return true;
1649        }
1650
1651        // PACI packets are partition heads
1652        if header.is_paci_packet() {
1653            return true;
1654        }
1655
1656        // For FU packets, only those with S (start) flag are partition heads
1657        if header.is_fragmentation_unit() {
1658            if payload.len() < H265NALU_HEADER_SIZE + 1 {
1659                return false;
1660            }
1661            let fu_header = H265FragmentationUnitHeader(payload[2]);
1662            return fu_header.s();
1663        }
1664
1665        false
1666    }
1667
1668    fn is_partition_tail(&self, marker: bool, payload: &[u8]) -> bool {
1669        if payload.len() < H265NALU_HEADER_SIZE {
1670            return false;
1671        }
1672
1673        let header = H265NALUHeader::new(payload[0], payload[1]);
1674
1675        // For FU packets, check E (end) flag
1676        if header.is_fragmentation_unit() {
1677            if payload.len() < H265NALU_HEADER_SIZE + 1 {
1678                return false;
1679            }
1680            let fu_header = H265FragmentationUnitHeader(payload[2]);
1681            return fu_header.e();
1682        }
1683
1684        // For all other packet types, rely on RTP marker bit
1685        marker
1686    }
1687}
1688
1689#[cfg(test)]
1690mod test {
1691    use super::*;
1692
1693    type Result<T> = std::result::Result<T, PacketError>;
1694
1695    // ========== Shared Test Utilities ==========
1696
1697    fn reconstruct_from_fu_packets(packets: &[Vec<u8>]) -> Vec<u8> {
1698        // Reconstruct the original NAL unit from a sequence of FU packets.
1699        // Assumes all packets are FU (type 49) and are consecutive.
1700        //
1701        // FU payloads are:
1702        //   [0..2)  : PayloadHdr (type=49)
1703        //   [2]     : FU header (S/E/type)
1704        //   [3..]   : fragment bytes
1705        const TYPE_MASK: u16 = 0b0111111 << 9; // bits 14..9
1706
1707        let mut out = Vec::new();
1708        let mut started = false;
1709
1710        for pkt in packets {
1711            assert!(pkt.len() >= 3);
1712            let hdr = H265NALUHeader::new(pkt[0], pkt[1]);
1713            assert!(hdr.is_fragmentation_unit());
1714
1715            let fu = H265FragmentationUnitHeader(pkt[2]);
1716
1717            if fu.s() {
1718                // Rebuild the original 2-byte NAL header by replacing Type with fu_type.
1719                let fu_u16 = u16::from_be_bytes([pkt[0], pkt[1]]);
1720                let orig_u16 = (fu_u16 & !TYPE_MASK) | ((fu.fu_type() as u16) << 9);
1721                out.extend_from_slice(&orig_u16.to_be_bytes());
1722                started = true;
1723            }
1724
1725            assert!(started, "FU sequence must start with S=1");
1726            out.extend_from_slice(&pkt[3..]);
1727        }
1728
1729        out
1730    }
1731
1732    /// RFC 7798 bitfield correctness tests.
1733    /// These are "unit tests" for header parsing and classification.
1734    mod header_tests {
1735        use super::*;
1736
1737        /// Test H.265 NAL Unit header parsing and field extraction.
1738        /// Verifies F bit, NAL type, layer_id, tid, and packet type detection (AP/FU/PACI).
1739        #[test]
1740        fn test_h265_nalu_header() -> Result<()> {
1741            #[derive(Default)]
1742            struct TestType {
1743                raw_header: &'static [u8],
1744
1745                fbit: bool,
1746                typ: u8,
1747                layer_id: u8,
1748                tid: u8,
1749
1750                is_ap: bool,
1751                is_fu: bool,
1752                is_paci: bool,
1753            }
1754
1755            let tests = vec![
1756                // fbit
1757                TestType {
1758                    raw_header: &[0x80, 0x00],
1759                    typ: 0,
1760                    layer_id: 0,
1761                    tid: 0,
1762                    fbit: true,
1763                    ..Default::default()
1764                },
1765                // VPS_NUT
1766                TestType {
1767                    raw_header: &[0x40, 0x01],
1768                    typ: 32,
1769                    layer_id: 0,
1770                    tid: 1,
1771                    ..Default::default()
1772                },
1773                // SPS_NUT
1774                TestType {
1775                    raw_header: &[0x42, 0x01],
1776                    typ: 33,
1777                    layer_id: 0,
1778                    tid: 1,
1779                    ..Default::default()
1780                },
1781                // PPS_NUT
1782                TestType {
1783                    raw_header: &[0x44, 0x01],
1784                    typ: 34,
1785                    layer_id: 0,
1786                    tid: 1,
1787                    ..Default::default()
1788                },
1789                // PREFIX_SEI_NUT
1790                TestType {
1791                    raw_header: &[0x4e, 0x01],
1792                    typ: 39,
1793                    layer_id: 0,
1794                    tid: 1,
1795                    ..Default::default()
1796                },
1797                // Fragmentation Unit
1798                TestType {
1799                    raw_header: &[0x62, 0x01],
1800                    typ: H265NALU_FRAGMENTATION_UNIT_TYPE,
1801                    layer_id: 0,
1802                    tid: 1,
1803                    is_fu: true,
1804                    ..Default::default()
1805                },
1806                // Aggregation Packet (Type 48)
1807                TestType {
1808                    raw_header: &[0x60, 0x01],
1809                    typ: H265NALU_AGGREGATION_PACKET_TYPE,
1810                    layer_id: 0,
1811                    tid: 1,
1812                    is_ap: true,
1813                    ..Default::default()
1814                },
1815                // PACI Packet (Type 50)
1816                TestType {
1817                    raw_header: &[0x64, 0x01],
1818                    typ: H265NALU_PACI_PACKET_TYPE,
1819                    layer_id: 0,
1820                    tid: 1,
1821                    is_paci: true,
1822                    ..Default::default()
1823                },
1824            ];
1825
1826            for cur in tests {
1827                let header = H265NALUHeader::new(cur.raw_header[0], cur.raw_header[1]);
1828
1829                assert_eq!(header.f(), cur.fbit, "invalid F bit");
1830                assert_eq!(header.nalu_type(), cur.typ, "invalid type");
1831
1832                // For any type < 32, NAL is a VLC NAL unit.
1833                assert_eq!(
1834                    header.is_type_vcl_unit(),
1835                    (header.nalu_type() < 32),
1836                    "invalid IsTypeVCLUnit"
1837                );
1838                assert_eq!(
1839                    header.is_aggregation_packet(),
1840                    cur.is_ap,
1841                    "invalid type (aggregation packet)"
1842                );
1843                assert_eq!(
1844                    header.is_fragmentation_unit(),
1845                    cur.is_fu,
1846                    "invalid type (fragmentation unit)"
1847                );
1848                assert_eq!(header.is_paci_packet(), cur.is_paci, "invalid type (PACI)");
1849                assert_eq!(header.layer_id(), cur.layer_id, "invalid layer_id");
1850                assert_eq!(header.tid(), cur.tid, "invalid tid");
1851            }
1852
1853            Ok(())
1854        }
1855
1856        /// Test IRAP (Intra Random Access Point) picture detection.
1857        /// Verifies that BLA, IDR, and CRA NAL types are correctly identified as IRAP frames.
1858        #[test]
1859        fn test_h265_irap_detection() -> Result<()> {
1860            // Test that is_irap() detects all IRAP types (BLA, IDR, CRA)
1861            // BLA_W_LP (16)
1862            let header = H265NALUHeader::new(0x20, 0x01);
1863            assert!(header.is_irap(), "BLA_W_LP should be detected as IRAP");
1864            assert!(!header.is_idr_picture(), "BLA_W_LP is not an IDR");
1865
1866            // BLA_W_RADL (17)
1867            let header = H265NALUHeader::new(0x22, 0x01);
1868            assert!(header.is_irap(), "BLA_W_RADL should be detected as IRAP");
1869            assert!(!header.is_idr_picture(), "BLA_W_RADL is not an IDR");
1870
1871            // BLA_N_LP (18)
1872            let header = H265NALUHeader::new(0x24, 0x01);
1873            assert!(header.is_irap(), "BLA_N_LP should be detected as IRAP");
1874            assert!(!header.is_idr_picture(), "BLA_N_LP is not an IDR");
1875
1876            // IDR_W_RADL (19)
1877            let header = H265NALUHeader::new(0x26, 0x01);
1878            assert!(header.is_irap(), "IDR_W_RADL should be detected as IRAP");
1879            assert!(header.is_idr_picture(), "IDR_W_RADL is an IDR");
1880
1881            // IDR_N_LP (20)
1882            let header = H265NALUHeader::new(0x28, 0x01);
1883            assert!(header.is_irap(), "IDR_N_LP should be detected as IRAP");
1884            assert!(header.is_idr_picture(), "IDR_N_LP is an IDR");
1885
1886            // CRA_NUT (21)
1887            let header = H265NALUHeader::new(0x2a, 0x01);
1888            assert!(header.is_irap(), "CRA_NUT should be detected as IRAP");
1889            assert!(!header.is_idr_picture(), "CRA_NUT is not an IDR");
1890
1891            // TRAIL_R (1) - not an IRAP
1892            let header = H265NALUHeader::new(0x02, 0x01);
1893            assert!(!header.is_irap(), "TRAIL_R should not be detected as IRAP");
1894            assert!(!header.is_idr_picture(), "TRAIL_R is not an IDR");
1895
1896            // VPS (32) - not an IRAP
1897            let header = H265NALUHeader::new(0x40, 0x01);
1898            assert!(!header.is_irap(), "VPS should not be detected as IRAP");
1899            assert!(!header.is_idr_picture(), "VPS is not an IDR");
1900
1901            // RADL_R (6) – not IRAP
1902            let header = H265NALUHeader::new(0x0c, 0x01); // 6 << 1
1903            assert!(!header.is_irap());
1904
1905            // RASL_R (9) – not IRAP
1906            let header = H265NALUHeader::new(0x12, 0x01); // 9 << 1
1907            assert!(!header.is_irap());
1908
1909            // Prefix SEI (39)
1910            let header = H265NALUHeader::new(0x4e, 0x01); // 39 << 1
1911            assert!(!header.is_irap());
1912
1913            Ok(())
1914        }
1915
1916        /// Test Fragmentation Unit (FU) header parsing.
1917        /// Verifies S (start), E (end) flags and fragmented NAL type extraction.
1918        #[test]
1919        fn test_h265_fu_header() -> Result<()> {
1920            #[derive(Default)]
1921            struct TestType {
1922                header: H265FragmentationUnitHeader,
1923                s: bool,
1924                e: bool,
1925                typ: u8,
1926            }
1927
1928            let tests = vec![
1929                // Start | IDR_W_RADL
1930                TestType {
1931                    header: H265FragmentationUnitHeader(0x93),
1932                    s: true,
1933                    e: false,
1934                    typ: 19,
1935                },
1936                // Continuation | IDR_W_RADL
1937                TestType {
1938                    header: H265FragmentationUnitHeader(0x13),
1939                    s: false,
1940                    e: false,
1941                    typ: 19,
1942                },
1943                // End | IDR_W_RADL
1944                TestType {
1945                    header: H265FragmentationUnitHeader(0x53),
1946                    s: false,
1947                    e: true,
1948                    typ: 19,
1949                },
1950                // Start | TRAIL_R
1951                TestType {
1952                    header: H265FragmentationUnitHeader(0x81),
1953                    s: true,
1954                    e: false,
1955                    typ: 1,
1956                },
1957                // Continuation | TRAIL_R
1958                TestType {
1959                    header: H265FragmentationUnitHeader(0x01),
1960                    s: false,
1961                    e: false,
1962                    typ: 1,
1963                },
1964                // End | TRAIL_R
1965                TestType {
1966                    header: H265FragmentationUnitHeader(0x41),
1967                    s: false,
1968                    e: true,
1969                    typ: 1,
1970                },
1971                // Invalid: S=1 and E=1 simultaneously (illegal per RFC 7798)
1972                TestType {
1973                    header: H265FragmentationUnitHeader(0xD3),
1974                    s: true,
1975                    e: true,
1976                    typ: 19,
1977                },
1978                // Illegal FU: VPS (type 32) must not be fragmented
1979                TestType {
1980                    header: H265FragmentationUnitHeader(0xA0),
1981                    s: true,
1982                    e: false,
1983                    typ: 32,
1984                },
1985            ];
1986
1987            for cur in tests {
1988                assert_eq!(cur.header.s(), cur.s, "invalid s field");
1989                assert_eq!(cur.header.e(), cur.e, "invalid e field");
1990                assert_eq!(cur.header.fu_type(), cur.typ, "invalid FuType field");
1991            }
1992
1993            Ok(())
1994        }
1995    } // end header_tests
1996
1997    /// Tests for RTP payload → NAL unit parsing.
1998    /// Validates Single NAL, AP, FU, PACI, and TSCI packet formats.
1999    mod parse_tests {
2000        use super::*;
2001
2002        /// Test Single NAL Unit packet depacketization.
2003        /// Verifies parsing of single NAL packets with and without DONL, including error cases.
2004        #[test]
2005        fn test_h265_single_nalunit_packet() -> Result<()> {
2006            #[derive(Default)]
2007            struct TestType {
2008                raw: &'static [u8],
2009                with_donl: bool,
2010                expected_packet: Option<H265SingleNALUnitPacket>,
2011                expected_err: Option<PacketError>,
2012            }
2013
2014            let tests = vec![
2015                TestType {
2016                    raw: &[],
2017                    expected_err: Some(PacketError::ErrShortPacket),
2018                    ..Default::default()
2019                },
2020                TestType {
2021                    raw: &[0x62],
2022                    expected_err: Some(PacketError::ErrShortPacket),
2023                    ..Default::default()
2024                },
2025                TestType {
2026                    raw: &[0x62, 0x01, 0x93],
2027                    expected_err: Some(PacketError::ErrShortPacket),
2028                    ..Default::default()
2029                },
2030                // FBit enabled in H265NALUHeader
2031                TestType {
2032                    raw: &[0x80, 0x01, 0x93, 0xaf, 0xaf, 0xaf, 0xaf],
2033                    expected_err: Some(PacketError::ErrH265CorruptedPacket),
2034                    ..Default::default()
2035                },
2036                // Type '49' in H265NALUHeader
2037                TestType {
2038                    raw: &[0x62, 0x01, 0x93, 0xaf, 0xaf, 0xaf, 0xaf],
2039                    expected_err: Some(PacketError::ErrInvalidH265PacketType),
2040                    ..Default::default()
2041                },
2042                // Type '50' in H265NALUHeader
2043                TestType {
2044                    raw: &[0x64, 0x01, 0x93, 0xaf, 0xaf, 0xaf, 0xaf],
2045                    expected_err: Some(PacketError::ErrInvalidH265PacketType),
2046                    ..Default::default()
2047                },
2048                TestType {
2049                    raw: &[0x01, 0x01, 0xab, 0xcd, 0xef],
2050                    expected_packet: Some(H265SingleNALUnitPacket {
2051                        payload_header: H265NALUHeader::new(0x01, 0x01),
2052                        payload: vec![0xab, 0xcd, 0xef],
2053                        ..Default::default()
2054                    }),
2055                    ..Default::default()
2056                },
2057                // DONL, payload too small
2058                TestType {
2059                    raw: &[0x01, 0x01, 0x93, 0xaf],
2060                    expected_err: Some(PacketError::ErrShortPacket),
2061                    with_donl: true,
2062                    ..Default::default()
2063                },
2064                TestType {
2065                    raw: &[0x01, 0x01, 0xaa, 0xbb, 0xcc],
2066                    expected_packet: Some(H265SingleNALUnitPacket {
2067                        payload_header: H265NALUHeader::new(0x01, 0x01),
2068                        donl: Some((0xaa << 8) | 0xbb),
2069                        payload: vec![0xcc],
2070                        ..Default::default()
2071                    }),
2072                    with_donl: true,
2073                    ..Default::default()
2074                },
2075                // IDR_W_RADL (19)
2076                TestType {
2077                    raw: &[0x26, 0x01, 0xde, 0xad, 0xbe, 0xef],
2078                    expected_packet: Some(H265SingleNALUnitPacket {
2079                        payload_header: H265NALUHeader::new(0x26, 0x01),
2080                        payload: vec![0xde, 0xad, 0xbe, 0xef],
2081                        ..Default::default()
2082                    }),
2083                    ..Default::default()
2084                },
2085                // CRA_NUT (21)
2086                TestType {
2087                    raw: &[0x2a, 0x01, 0xaa, 0xbb],
2088                    expected_packet: Some(H265SingleNALUnitPacket {
2089                        payload_header: H265NALUHeader::new(0x2a, 0x01),
2090                        payload: vec![0xaa, 0xbb],
2091                        ..Default::default()
2092                    }),
2093                    ..Default::default()
2094                },
2095                // type=1, layer_id=3, tid=2
2096                TestType {
2097                    raw: &[0x01, 0x32, 0x99, 0x88],
2098                    expected_packet: Some(H265SingleNALUnitPacket {
2099                        payload_header: H265NALUHeader::new(0x01, 0x32),
2100                        payload: vec![0x99, 0x88],
2101                        ..Default::default()
2102                    }),
2103                    ..Default::default()
2104                },
2105                // IDR with DONL
2106                TestType {
2107                    raw: &[0x26, 0x01, 0x12, 0x34, 0xaa, 0xbb],
2108                    expected_packet: Some(H265SingleNALUnitPacket {
2109                        payload_header: H265NALUHeader::new(0x26, 0x01),
2110                        donl: Some(0x1234),
2111                        payload: vec![0xaa, 0xbb],
2112                        ..Default::default()
2113                    }),
2114                    with_donl: true,
2115                    ..Default::default()
2116                },
2117                TestType {
2118                    raw: &[0x26, 0x01, 0x12, 0x34, 0xaa, 0xbb],
2119                    with_donl: true,
2120                    expected_packet: Some(H265SingleNALUnitPacket {
2121                        payload_header: H265NALUHeader::new(0x26, 0x01),
2122                        donl: Some(0x1234),
2123                        payload: vec![0xaa, 0xbb],
2124                        ..Default::default()
2125                    }),
2126                    ..Default::default()
2127                },
2128            ];
2129
2130            for cur in tests {
2131                let mut parsed = H265SingleNALUnitPacket::default();
2132                if cur.with_donl {
2133                    parsed.with_donl(cur.with_donl);
2134                }
2135
2136                let result = parsed.depacketize(&cur.raw);
2137
2138                if cur.expected_err.is_some() && result.is_ok() {
2139                    assert!(false, "should error");
2140                } else if cur.expected_err.is_none() && result.is_err() {
2141                    assert!(false, "should not error");
2142                }
2143
2144                if let Some(expected_packet) = cur.expected_packet {
2145                    assert_eq!(
2146                        expected_packet.payload_header(),
2147                        parsed.payload_header(),
2148                        "invalid payload header"
2149                    );
2150                    assert_eq!(expected_packet.donl(), parsed.donl(), "invalid DONL");
2151
2152                    assert_eq!(
2153                        expected_packet.payload(),
2154                        parsed.payload(),
2155                        "invalid payload"
2156                    );
2157                }
2158            }
2159
2160            Ok(())
2161        }
2162
2163        /// Test Aggregation Packet (AP) depacketization.
2164        /// Verifies parsing of multiple NAL units in one packet with DONL/DOND fields.
2165        #[test]
2166        fn test_h265_aggregation_packet() -> Result<()> {
2167            #[derive(Default)]
2168            struct TestType {
2169                raw: &'static [u8],
2170                with_donl: bool,
2171                expected_packet: Option<H265AggregationPacket>,
2172                expected_err: Option<PacketError>,
2173            }
2174
2175            let tests = vec![
2176                TestType {
2177                    raw: &[],
2178                    expected_err: Some(PacketError::ErrShortPacket),
2179                    ..Default::default()
2180                },
2181                TestType {
2182                    raw: &[0x62],
2183                    expected_err: Some(PacketError::ErrShortPacket),
2184                    ..Default::default()
2185                },
2186                TestType {
2187                    raw: &[0x62, 0x01, 0x93],
2188                    expected_err: Some(PacketError::ErrShortPacket),
2189                    ..Default::default()
2190                },
2191                // FBit enabled in H265NALUHeader
2192                TestType {
2193                    raw: &[0x80, 0x01, 0x93, 0xaf, 0xaf, 0xaf, 0xaf],
2194                    expected_err: Some(PacketError::ErrH265CorruptedPacket),
2195                    ..Default::default()
2196                },
2197                // Type '48' in H265NALUHeader
2198                TestType {
2199                    raw: &[0xE0, 0x01, 0x93, 0xaf, 0xaf, 0xaf, 0xaf],
2200                    expected_err: Some(PacketError::ErrInvalidH265PacketType),
2201                    ..Default::default()
2202                },
2203                // Small payload
2204                TestType {
2205                    raw: &[0x60, 0x01, 0x00, 0x1],
2206                    expected_err: Some(PacketError::ErrShortPacket),
2207                    ..Default::default()
2208                },
2209                // Small payload
2210                TestType {
2211                    raw: &[0x60, 0x01, 0x00],
2212                    expected_err: Some(PacketError::ErrShortPacket),
2213                    with_donl: true,
2214                    ..Default::default()
2215                },
2216                // Small payload
2217                TestType {
2218                    raw: &[0x60, 0x01, 0x00, 0x1],
2219                    expected_err: Some(PacketError::ErrShortPacket),
2220                    with_donl: true,
2221                    ..Default::default()
2222                },
2223                // Small payload
2224                TestType {
2225                    raw: &[0x60, 0x01, 0x00, 0x01, 0x02],
2226                    expected_err: Some(PacketError::ErrShortPacket),
2227                    with_donl: true,
2228                    ..Default::default()
2229                },
2230                // Single Aggregation Unit
2231                TestType {
2232                    raw: &[0x60, 0x01, 0x00, 0x01, 0x00, 0x02, 0x00, 0x00],
2233                    expected_err: Some(PacketError::ErrShortPacket),
2234                    with_donl: true,
2235                    ..Default::default()
2236                },
2237                // Incomplete second Aggregation Unit
2238                TestType {
2239                    raw: &[
2240                        0x60, 0x01, 0x00, 0x01, 0x00, 0x02, 0x00, 0x00, // DONL
2241                        0x00,
2242                    ],
2243                    expected_err: Some(PacketError::ErrShortPacket),
2244                    with_donl: true,
2245                    ..Default::default()
2246                },
2247                // Incomplete second Aggregation Unit
2248                TestType {
2249                    raw: &[
2250                        0x60, 0x01, 0x00, 0x01, 0x00, 0x02, 0x00, 0x00,
2251                        // DONL, NAL Unit size (2 bytes)
2252                        0x00, 0x55, 0x55,
2253                    ],
2254                    expected_err: Some(PacketError::ErrShortPacket),
2255                    with_donl: true,
2256                    ..Default::default()
2257                },
2258                // Valid Second Aggregation Unit
2259                TestType {
2260                    raw: &[
2261                        0x60, 0x01, 0xcc, 0xdd, 0x00, 0x02, 0xff, 0xee,
2262                        // DONL, NAL Unit size (2 bytes), Payload
2263                        0x77, 0x00, 0x01, 0xaa,
2264                    ],
2265                    with_donl: true,
2266                    expected_packet: Some(H265AggregationPacket {
2267                        first_unit: Some(H265AggregationUnitFirst {
2268                            donl: Some(0xccdd),
2269                            nal_unit_size: 2,
2270                            nal_unit: vec![0xff, 0xee],
2271                        }),
2272                        other_units: vec![H265AggregationUnit {
2273                            dond: Some(0x77),
2274                            nal_unit_size: 1,
2275                            nal_unit: vec![0xaa],
2276                        }],
2277                        might_need_donl: false,
2278                    }),
2279                    ..Default::default()
2280                },
2281                // Valid AP WITHOUT DONL/DOND (with_donl = false)
2282                // Requires: first unit + at least 1 other unit
2283                TestType {
2284                    raw: &[
2285                        0x60, 0x01, // AP payload header (Type=48)
2286                        0x00, 0x02, // first NALU size = 2
2287                        0x11, 0x22, // first NALU
2288                        0x00, 0x01, // second NALU size = 1
2289                        0x33, // second NALU
2290                    ],
2291                    with_donl: false,
2292                    expected_packet: Some(H265AggregationPacket {
2293                        first_unit: Some(H265AggregationUnitFirst {
2294                            donl: None,
2295                            nal_unit_size: 2,
2296                            nal_unit: vec![0x11, 0x22],
2297                        }),
2298                        other_units: vec![H265AggregationUnit {
2299                            dond: None,
2300                            nal_unit_size: 1,
2301                            nal_unit: vec![0x33],
2302                        }],
2303                        might_need_donl: false,
2304                    }),
2305                    ..Default::default()
2306                },
2307                // Valid AP WITH DONL + multiple other units (exercise DOND parsing twice)
2308                // Includes DOND=0 and another DOND value
2309                TestType {
2310                    raw: &[
2311                        0x60, 0x01, // AP payload header (Type=48)
2312                        0x00, 0x10, // DONL = 0x0010
2313                        0x00, 0x01, // first NALU size = 1
2314                        0xaa, // first NALU
2315                        0x00, // DOND for 2nd AU
2316                        0x00, 0x01, // second NALU size = 1
2317                        0xbb, // second NALU
2318                        0x05, // DOND for 3rd AU
2319                        0x00, 0x02, // third NALU size = 2
2320                        0xcc, 0xdd, // third NALU
2321                    ],
2322                    with_donl: true,
2323                    expected_packet: Some(H265AggregationPacket {
2324                        first_unit: Some(H265AggregationUnitFirst {
2325                            donl: Some(0x0010),
2326                            nal_unit_size: 1,
2327                            nal_unit: vec![0xaa],
2328                        }),
2329                        other_units: vec![
2330                            H265AggregationUnit {
2331                                dond: Some(0x00),
2332                                nal_unit_size: 1,
2333                                nal_unit: vec![0xbb],
2334                            },
2335                            H265AggregationUnit {
2336                                dond: Some(0x05),
2337                                nal_unit_size: 2,
2338                                nal_unit: vec![0xcc, 0xdd],
2339                            },
2340                        ],
2341                        might_need_donl: false,
2342                    }),
2343                    ..Default::default()
2344                },
2345                // “Forgiving tail” behavior (with_donl=false):
2346                // After parsing one valid other unit, an incomplete next unit causes a BREAK (not error).
2347                TestType {
2348                    raw: &[
2349                        0x60, 0x01, // AP payload header (Type=48)
2350                        0x00, 0x01, // first NALU size = 1
2351                        0x11, // first NALU
2352                        0x00, 0x01, // second NALU size = 1
2353                        0x22, // second NALU
2354                        0x99, // trailing junk: not enough bytes for next 2-byte size => loop breaks
2355                    ],
2356                    with_donl: false,
2357                    expected_packet: Some(H265AggregationPacket {
2358                        first_unit: Some(H265AggregationUnitFirst {
2359                            donl: None,
2360                            nal_unit_size: 1,
2361                            nal_unit: vec![0x11],
2362                        }),
2363                        other_units: vec![H265AggregationUnit {
2364                            dond: None,
2365                            nal_unit_size: 1,
2366                            nal_unit: vec![0x22],
2367                        }],
2368                        might_need_donl: false,
2369                    }),
2370                    ..Default::default()
2371                },
2372                // "Forgiving tail" behavior (with_donl=true):
2373                // Trailing single DOND byte is read, then payload.len()<2 => BREAK, but
2374                // since we already parsed one unit, OK.
2375                TestType {
2376                    raw: &[
2377                        0x60, 0x01, // AP payload header (Type=48)
2378                        0x12, 0x34, // DONL
2379                        0x00, 0x01, // first NALU size = 1
2380                        0xaa, // first NALU
2381                        0x01, // DOND for 2nd AU
2382                        0x00, 0x01, // second NALU size = 1
2383                        0xbb, // second NALU
2384                        0x55, // trailing DOND only, no size => break (and still succeed)
2385                    ],
2386                    with_donl: true,
2387                    expected_packet: Some(H265AggregationPacket {
2388                        first_unit: Some(H265AggregationUnitFirst {
2389                            donl: Some(0x1234),
2390                            nal_unit_size: 1,
2391                            nal_unit: vec![0xaa],
2392                        }),
2393                        other_units: vec![H265AggregationUnit {
2394                            dond: Some(0x01),
2395                            nal_unit_size: 1,
2396                            nal_unit: vec![0xbb],
2397                        }],
2398                        might_need_donl: false,
2399                    }),
2400                    ..Default::default()
2401                },
2402                // Wrong outer header type: FU (49) should be rejected by AP depacketizer
2403                TestType {
2404                    raw: &[
2405                        0x62, 0x01, // Type=49 (FU), not AP
2406                        0x00, 0x01, 0xaa, // extra bytes, just to avoid short-packet path
2407                    ],
2408                    expected_err: Some(PacketError::ErrInvalidH265PacketType),
2409                    ..Default::default()
2410                },
2411                // Wrong outer header type: PACI (50) should be rejected by AP depacketizer
2412                TestType {
2413                    raw: &[
2414                        0x64, 0x01, // Type=50 (PACI), not AP
2415                        0x00, 0x01, 0xaa,
2416                    ],
2417                    expected_err: Some(PacketError::ErrInvalidH265PacketType),
2418                    ..Default::default()
2419                },
2420                TestType {
2421                    raw: &[
2422                        0x60, 0x01, 0x12, 0x34, // DONL = 0x1234
2423                        0x00, 0x01, 0xaa, 0x05, // DOND = +5
2424                        0x00, 0x01, 0xbb, 0xFE, // DOND = -2 (wrap)
2425                        0x00, 0x01, 0xcc,
2426                    ],
2427                    with_donl: true,
2428                    expected_packet: Some(H265AggregationPacket {
2429                        first_unit: Some(H265AggregationUnitFirst {
2430                            donl: Some(0x1234),
2431                            nal_unit_size: 1,
2432                            nal_unit: vec![0xaa],
2433                        }),
2434                        other_units: vec![
2435                            H265AggregationUnit {
2436                                dond: Some(0x05),
2437                                nal_unit_size: 1,
2438                                nal_unit: vec![0xbb],
2439                            },
2440                            H265AggregationUnit {
2441                                dond: Some(0xFE),
2442                                nal_unit_size: 1,
2443                                nal_unit: vec![0xcc],
2444                            },
2445                        ],
2446                        might_need_donl: false,
2447                    }),
2448                    ..Default::default()
2449                },
2450            ];
2451
2452            for cur in tests {
2453                let mut parsed = H265AggregationPacket::default();
2454                if cur.with_donl {
2455                    parsed.with_donl(cur.with_donl);
2456                }
2457
2458                let result = parsed.depacketize(&cur.raw);
2459
2460                if cur.expected_err.is_some() && result.is_ok() {
2461                    assert!(false, "should error");
2462                } else if cur.expected_err.is_none() && result.is_err() {
2463                    assert!(false, "should not error");
2464                }
2465
2466                if let Some(expected_packet) = cur.expected_packet {
2467                    if let (Some(first_unit), Some(parsed_first_unit)) =
2468                        (expected_packet.first_unit(), parsed.first_unit())
2469                    {
2470                        assert_eq!(
2471                            parsed_first_unit.nal_unit_size, first_unit.nal_unit_size,
2472                            "invalid first unit NALUSize"
2473                        );
2474                        assert_eq!(
2475                            first_unit.donl(),
2476                            parsed_first_unit.donl(),
2477                            "invalid first unit DONL"
2478                        );
2479                        assert_eq!(
2480                            first_unit.nal_unit(),
2481                            parsed_first_unit.nal_unit(),
2482                            "invalid first unit NalUnit"
2483                        );
2484                    }
2485
2486                    assert_eq!(
2487                        expected_packet.other_units().len(),
2488                        parsed.other_units().len(),
2489                        "number of other units mismatch"
2490                    );
2491
2492                    for ndx in 0..expected_packet.other_units().len() {
2493                        assert_eq!(
2494                            parsed.other_units()[ndx].nalu_size(),
2495                            expected_packet.other_units()[ndx].nalu_size(),
2496                            "invalid unit NALUSize"
2497                        );
2498
2499                        assert_eq!(
2500                            expected_packet.other_units()[ndx].dond(),
2501                            parsed.other_units()[ndx].dond(),
2502                            "invalid unit DOND"
2503                        );
2504
2505                        assert_eq!(
2506                            expected_packet.other_units()[ndx].nal_unit(),
2507                            parsed.other_units()[ndx].nal_unit(),
2508                            "invalid first unit NalUnit"
2509                        );
2510                    }
2511
2512                    assert_eq!(
2513                        expected_packet.other_units(),
2514                        parsed.other_units(),
2515                        "invalid payload"
2516                    );
2517                }
2518            }
2519
2520            Ok(())
2521        }
2522
2523        /// Test Fragmentation Unit (FU) packet depacketization.
2524        /// Verifies parsing of fragmented large NAL units with and without DONL.
2525        #[test]
2526        fn test_h265_fragmentation_unit_packet() -> Result<()> {
2527            #[derive(Default)]
2528            struct TestType {
2529                raw: &'static [u8],
2530                with_donl: bool,
2531                expected_fu: Option<H265FragmentationUnitPacket>,
2532                expected_err: Option<PacketError>,
2533            }
2534            let tests = vec![
2535                TestType {
2536                    raw: &[],
2537                    expected_err: Some(PacketError::ErrShortPacket),
2538                    ..Default::default()
2539                },
2540                TestType {
2541                    raw: &[0x62],
2542                    expected_err: Some(PacketError::ErrShortPacket),
2543                    ..Default::default()
2544                },
2545                TestType {
2546                    raw: &[0x62, 0x01],
2547                    expected_err: Some(PacketError::ErrShortPacket),
2548                    ..Default::default()
2549                },
2550                TestType {
2551                    raw: &[0x62, 0x01, 0x93],
2552                    expected_err: Some(PacketError::ErrShortPacket),
2553                    ..Default::default()
2554                },
2555                // FBit enabled in H265NALUHeader
2556                TestType {
2557                    raw: &[0x80, 0x01, 0x93, 0xaf],
2558                    expected_err: Some(PacketError::ErrH265CorruptedPacket),
2559                    ..Default::default()
2560                },
2561                // Type not '49' in H265NALUHeader
2562                TestType {
2563                    raw: &[0x40, 0x01, 0x93, 0xaf],
2564                    expected_err: Some(PacketError::ErrInvalidH265PacketType),
2565                    ..Default::default()
2566                },
2567                TestType {
2568                    raw: &[0x62, 0x01, 0x93, 0xaf],
2569                    expected_fu: Some(H265FragmentationUnitPacket {
2570                        payload_header: H265NALUHeader::new(0x62, 0x01),
2571                        fu_header: H265FragmentationUnitHeader(0x93),
2572                        donl: None,
2573                        payload: vec![0xaf],
2574                        might_need_donl: false,
2575                    }),
2576                    ..Default::default()
2577                },
2578                TestType {
2579                    raw: &[0x62, 0x01, 0x93, 0xcc],
2580                    with_donl: true,
2581                    expected_err: Some(PacketError::ErrShortPacket),
2582                    ..Default::default()
2583                },
2584                TestType {
2585                    raw: &[0x62, 0x01, 0x93, 0xcc, 0xdd, 0xaf, 0x0d, 0x5a],
2586                    with_donl: true,
2587                    expected_fu: Some(H265FragmentationUnitPacket {
2588                        payload_header: H265NALUHeader::new(0x62, 0x01),
2589                        fu_header: H265FragmentationUnitHeader(0x93),
2590                        donl: Some((0xcc << 8) | 0xdd),
2591                        payload: vec![0xaf, 0x0d, 0x5a],
2592                        might_need_donl: false,
2593                    }),
2594                    ..Default::default()
2595                },
2596            ];
2597
2598            for cur in tests {
2599                let mut parsed = H265FragmentationUnitPacket::default();
2600                if cur.with_donl {
2601                    parsed.with_donl(cur.with_donl);
2602                }
2603
2604                let result = parsed.depacketize(&cur.raw);
2605
2606                if cur.expected_err.is_some() && result.is_ok() {
2607                    assert!(false, "should error");
2608                } else if cur.expected_err.is_none() && result.is_err() {
2609                    assert!(false, "should not error");
2610                }
2611
2612                if let Some(expected_fu) = &cur.expected_fu {
2613                    assert_eq!(
2614                        parsed.payload_header(),
2615                        expected_fu.payload_header(),
2616                        "invalid payload header"
2617                    );
2618                    assert_eq!(
2619                        parsed.fu_header(),
2620                        expected_fu.fu_header(),
2621                        "invalid FU header"
2622                    );
2623                    assert_eq!(parsed.donl(), expected_fu.donl(), "invalid DONL");
2624                    assert_eq!(parsed.payload(), expected_fu.payload(), "invalid Payload");
2625                }
2626            }
2627
2628            Ok(())
2629        }
2630
2631        /// Test TSCI (Temporal Scalability Control Information) field extraction.
2632        /// Verifies TL0PICIDX, IrapPicID, S, E, and RES bit parsing.
2633        #[test]
2634        fn test_h265_temporal_scalability_control_information() -> Result<()> {
2635            #[derive(Default)]
2636            struct TestType {
2637                value: H265TSCI,
2638                expected_tl0picidx: u8,
2639                expected_irap_pic_id: u8,
2640                expected_s: bool,
2641                expected_e: bool,
2642                expected_res: u8,
2643            }
2644
2645            let tests = vec![
2646                TestType {
2647                    value: H265TSCI(((0xCA) << 24) | ((0xFE) << 16)),
2648                    expected_tl0picidx: 0xCA,
2649                    expected_irap_pic_id: 0xFE,
2650                    ..Default::default()
2651                },
2652                TestType {
2653                    value: H265TSCI((1) << 15),
2654                    expected_s: true,
2655                    ..Default::default()
2656                },
2657                TestType {
2658                    value: H265TSCI((1) << 14),
2659                    expected_e: true,
2660                    ..Default::default()
2661                },
2662                TestType {
2663                    value: H265TSCI((0x0A) << 8),
2664                    expected_res: 0x0A,
2665                    ..Default::default()
2666                },
2667                // Sets RES, and force sets S and E to 0.
2668                TestType {
2669                    value: H265TSCI(
2670                        ((0xAA) << 8) & (u32::MAX ^ ((1) << 15)) & (u32::MAX ^ ((1) << 14)),
2671                    ),
2672                    expected_res: 0xAA & 0b00111111,
2673                    ..Default::default()
2674                },
2675            ];
2676
2677            for cur in tests {
2678                assert_eq!(
2679                    cur.value.tl0picidx(),
2680                    cur.expected_tl0picidx,
2681                    "invalid TL0PICIDX"
2682                );
2683                assert_eq!(
2684                    cur.value.irap_pic_id(),
2685                    cur.expected_irap_pic_id,
2686                    "invalid IrapPicID"
2687                );
2688                assert_eq!(cur.value.s(), cur.expected_s, "invalid S");
2689                assert_eq!(cur.value.e(), cur.expected_e, "invalid E");
2690                assert_eq!(cur.value.res(), cur.expected_res, "invalid RES");
2691            }
2692
2693            Ok(())
2694        }
2695
2696        /// Test PACI (Payload Content Information) packet depacketization.
2697        /// Verifies parsing of PACI headers, PHES extensions, and TSCI data.
2698        #[test]
2699        fn test_h265_paci_packet() -> Result<()> {
2700            #[derive(Default)]
2701            struct TestType {
2702                raw: &'static [u8],
2703                expected_fu: Option<H265PACIPacket>,
2704                expected_err: Option<PacketError>,
2705            }
2706
2707            let tests = vec![
2708                TestType {
2709                    raw: &[],
2710                    expected_err: Some(PacketError::ErrShortPacket),
2711                    ..Default::default()
2712                },
2713                TestType {
2714                    raw: &[0x62, 0x01, 0x93],
2715                    expected_err: Some(PacketError::ErrShortPacket),
2716                    ..Default::default()
2717                },
2718                // FBit enabled in H265NALUHeader
2719                TestType {
2720                    raw: &[0x80, 0x01, 0x93, 0xaf, 0xaf, 0xaf, 0xaf],
2721                    expected_err: Some(PacketError::ErrH265CorruptedPacket),
2722                    ..Default::default()
2723                },
2724                // Type not '50' in H265NALUHeader
2725                TestType {
2726                    raw: &[0x40, 0x01, 0x93, 0xaf, 0xaf, 0xaf, 0xaf],
2727                    expected_err: Some(PacketError::ErrInvalidH265PacketType),
2728                    ..Default::default()
2729                },
2730                // Invalid header extension size
2731                TestType {
2732                    raw: &[0x64, 0x01, 0x93, 0xaf, 0xaf, 0xaf, 0xaf],
2733                    expected_err: Some(PacketError::ErrInvalidH265PacketType),
2734                    ..Default::default()
2735                },
2736                // No Header Extension
2737                TestType {
2738                    raw: &[0x64, 0x01, 0x64, 0x00, 0xab, 0xcd, 0xef],
2739                    expected_fu: Some(H265PACIPacket {
2740                        payload_header: H265NALUHeader::new(0x64, 0x01),
2741                        paci_header_fields: ((0x64) << 8),
2742                        phes: vec![],
2743                        payload: vec![0xab, 0xcd, 0xef],
2744                    }),
2745                    ..Default::default()
2746                },
2747                // Header Extension 1 byte
2748                TestType {
2749                    raw: &[0x64, 0x01, 0x64, 0x10, 0xff, 0xab, 0xcd, 0xef],
2750                    expected_fu: Some(H265PACIPacket {
2751                        payload_header: H265NALUHeader::new(0x64, 0x01),
2752                        paci_header_fields: ((0x64) << 8) | (0x10),
2753                        phes: vec![0xff],
2754                        payload: vec![0xab, 0xcd, 0xef],
2755                    }),
2756                    ..Default::default()
2757                },
2758                // Header Extension TSCI
2759                TestType {
2760                    raw: &[
2761                        0x64, 0x01, 0x64, 0b00111000, 0xaa, 0xbb, 0x80, 0xab, 0xcd, 0xef,
2762                    ],
2763                    expected_fu: Some(H265PACIPacket {
2764                        payload_header: H265NALUHeader::new(0x64, 0x01),
2765                        paci_header_fields: ((0x64) << 8) | (0b00111000),
2766                        phes: vec![0xaa, 0xbb, 0x80],
2767                        payload: vec![0xab, 0xcd, 0xef],
2768                    }),
2769                    ..Default::default()
2770                },
2771            ];
2772
2773            for cur in tests {
2774                let mut parsed = H265PACIPacket::default();
2775
2776                let result = parsed.depacketize(&cur.raw);
2777
2778                if cur.expected_err.is_some() && result.is_ok() {
2779                    assert!(false, "should error");
2780                } else if cur.expected_err.is_none() && result.is_err() {
2781                    assert!(false, "should not error");
2782                }
2783
2784                if let Some(expected_fu) = &cur.expected_fu {
2785                    assert_eq!(
2786                        expected_fu.payload_header(),
2787                        parsed.payload_header(),
2788                        "invalid PayloadHeader"
2789                    );
2790                    assert_eq!(expected_fu.a(), parsed.a(), "invalid A");
2791                    assert_eq!(expected_fu.ctype(), parsed.ctype(), "invalid CType");
2792                    assert_eq!(expected_fu.phs_size(), parsed.phs_size(), "invalid PHSsize");
2793                    assert_eq!(expected_fu.f0(), parsed.f0(), "invalid F0");
2794                    assert_eq!(expected_fu.f1(), parsed.f1(), "invalid F1");
2795                    assert_eq!(expected_fu.f2(), parsed.f2(), "invalid F2");
2796                    assert_eq!(expected_fu.y(), parsed.y(), "invalid Y");
2797                    assert_eq!(expected_fu.phes(), parsed.phes(), "invalid PHES");
2798                    assert_eq!(expected_fu.payload(), parsed.payload(), "invalid Payload");
2799                    assert_eq!(expected_fu.tsci(), parsed.tsci(), "invalid TSCI");
2800                }
2801            }
2802
2803            Ok(())
2804        }
2805
2806        /// Test PACI packet creation (packetization).
2807        /// Verifies encoding of inner NAL units into PACI packets with various PHES sizes and flags.
2808        #[test]
2809        fn test_h265_paci_packetizer() -> Result<()> {
2810            // Test 1: Basic PACI packet with no PHES
2811            {
2812                let inner_nalu = vec![0x26, 0x01, 0xab, 0xcd, 0xef]; // Type 19 (IDR_W_RADL)
2813                let phes: &[u8] = &[];
2814                let mut buf = Vec::new();
2815
2816                let packet = H265PACIPacket::packetize(&inner_nalu, phes, &mut buf)?;
2817
2818                // Verify packet structure
2819                assert!(packet.len() >= 4, "PACI packet too short");
2820
2821                // Verify it's Type 50
2822                let header = H265NALUHeader::new(packet[0], packet[1]);
2823                assert_eq!(header.nalu_type(), H265NALU_PACI_PACKET_TYPE);
2824
2825                // Depacketize and verify
2826                let mut decoded = H265PACIPacket::default();
2827                decoded.depacketize(&packet)?;
2828
2829                assert_eq!(decoded.ctype(), 19); // IDR_W_RADL
2830                assert_eq!(decoded.phs_size(), 0);
2831                assert!(!decoded.f0());
2832                assert_eq!(decoded.payload(), vec![0xab, 0xcd, 0xef]);
2833            }
2834
2835            // Test 2: PACI packet with 1-byte PHES
2836            {
2837                let inner_nalu = vec![0x02, 0x01, 0xff, 0xee, 0xdd];
2838                let phes = vec![0xaa];
2839                let mut buf = Vec::new();
2840
2841                let packet = H265PACIPacket::packetize(&inner_nalu, &phes, &mut buf)?;
2842
2843                let mut decoded = H265PACIPacket::default();
2844                decoded.depacketize(&packet)?;
2845
2846                assert_eq!(decoded.ctype(), 1);
2847                assert_eq!(decoded.phs_size(), 1);
2848                assert!(!decoded.f0()); // F0 only set if PHES >= 3 bytes
2849                assert_eq!(decoded.phes(), vec![0xaa]);
2850                assert_eq!(decoded.payload(), vec![0xff, 0xee, 0xdd]);
2851            }
2852
2853            // Test 3: PACI packet with TSCI (3-byte PHES, F0=1)
2854            {
2855                let inner_nalu = vec![0x04, 0x01, 0x11, 0x22, 0x33];
2856                let phes = vec![0xca, 0xfe, 0x80]; // TSCI data
2857                let mut buf = Vec::new();
2858
2859                let packet = H265PACIPacket::packetize(&inner_nalu, &phes, &mut buf)?;
2860
2861                let mut decoded = H265PACIPacket::default();
2862                decoded.depacketize(&packet)?;
2863
2864                assert_eq!(decoded.ctype(), 2);
2865                assert_eq!(decoded.phs_size(), 3);
2866                assert!(decoded.f0()); // F0 set for TSCI
2867                assert_eq!(decoded.phes(), vec![0xca, 0xfe, 0x80]);
2868                assert_eq!(decoded.payload(), vec![0x11, 0x22, 0x33]);
2869            }
2870
2871            // Test 4: PACI with F bit set in inner NALU (A bit)
2872            {
2873                let inner_nalu = vec![0x80, 0x01, 0xaa]; // F bit set
2874                let phes: &[u8] = &[];
2875                let mut buf = Vec::new();
2876
2877                let packet = H265PACIPacket::packetize(&inner_nalu, phes, &mut buf)?;
2878
2879                let mut decoded = H265PACIPacket::default();
2880                // Depacketization will fail due to F bit in PACI header, but we check A bit is set
2881                // Actually, the PACI payload header shouldn't have F bit set - only inner does
2882                // Let's verify the PACI header fields have A bit set
2883                let paci_fields = ((packet[2] as u16) << 8) | (packet[3] as u16);
2884                let a_bit = (paci_fields & (1 << 15)) != 0;
2885                assert!(a_bit, "A bit should be set when inner NALU has F bit");
2886            }
2887
2888            // Test 5: PHES too long (>31 bytes) should error
2889            {
2890                let inner_nalu = vec![0x02, 0x01, 0xaa];
2891                let phes = vec![0u8; 32]; // 32 bytes - too long
2892                let mut buf = Vec::new();
2893
2894                let result = H265PACIPacket::packetize(&inner_nalu, &phes, &mut buf);
2895                assert!(result.is_err());
2896                assert_eq!(result.unwrap_err(), PacketError::ErrH265PACIPHESTooLong);
2897            }
2898
2899            // Test 6: Round-trip test with various layer_id and tid values
2900            {
2901                let inner_nalu = vec![0x12, 0xff, 0x12, 0x34]; // Type 9, layer_id=31, tid=7
2902                let phes = vec![0x11, 0x22];
2903                let mut buf = Vec::new();
2904
2905                let packet = H265PACIPacket::packetize(&inner_nalu, &phes, &mut buf)?;
2906
2907                let mut decoded = H265PACIPacket::default();
2908                decoded.depacketize(&packet)?;
2909
2910                // Verify PACI header preserved layer_id and tid from inner NALU
2911                assert_eq!(decoded.payload_header().layer_id(), 31);
2912                assert_eq!(decoded.payload_header().tid(), 7);
2913                assert_eq!(decoded.ctype(), 9);
2914                assert_eq!(decoded.phs_size(), 2);
2915                assert_eq!(decoded.phes(), vec![0x11, 0x22]);
2916                assert_eq!(decoded.payload(), vec![0x12, 0x34]);
2917            }
2918
2919            // Test 7: Minimal payload (1 byte) in inner NALU
2920            {
2921                let inner_nalu = vec![0x02, 0x01, 0xaa]; // Header + 1 byte payload
2922                let phes: &[u8] = &[];
2923                let mut buf = Vec::new();
2924
2925                let packet = H265PACIPacket::packetize(&inner_nalu, phes, &mut buf)?;
2926
2927                let mut decoded = H265PACIPacket::default();
2928                decoded.depacketize(&packet)?;
2929
2930                assert_eq!(decoded.ctype(), 1);
2931                assert_eq!(decoded.payload(), vec![0xaa]);
2932            }
2933
2934            Ok(())
2935        }
2936
2937        /// Test PACI packet round-trip with TSCI extension.
2938        /// Verifies that PACI packets with 3-byte TSCI data can be created and parsed correctly.
2939        #[test]
2940        fn test_h265_paci_roundtrip_with_tsci() -> Result<()> {
2941            // Create a PACI packet with TSCI extension and verify all fields survive round-trip
2942            let inner_nalu = vec![0x26, 0x01, 0xde, 0xad, 0xbe, 0xef]; // IDR_W_RADL
2943
2944            // Build TSCI: TL0PICIDX=0xAB, IrapPicID=0xCD, S=1, E=0, RES=0x05
2945            let tsci_bytes = vec![
2946                0xAB, // TL0PICIDX
2947                0xCD, // IrapPicID
2948                0x85, // S=1, E=0, RES=0x05
2949            ];
2950
2951            let mut buf = Vec::new();
2952            let packet = H265PACIPacket::packetize(&inner_nalu, &tsci_bytes, &mut buf)?;
2953
2954            // Depacketize
2955            let mut decoded = H265PACIPacket::default();
2956            decoded.depacketize(&packet)?;
2957
2958            // Verify TSCI is present and correct
2959            assert!(decoded.f0(), "F0 should be set for TSCI");
2960            let tsci = decoded.tsci().expect("TSCI should be present");
2961
2962            // Note: The TSCI constructor in the depacketizer has a bug (uses phes[0] three times)
2963            // But we're testing that our packetizer creates valid packets
2964            assert_eq!(decoded.phes(), tsci_bytes);
2965            assert_eq!(decoded.ctype(), 19); // IDR_W_RADL type
2966            assert_eq!(decoded.payload(), vec![0xde, 0xad, 0xbe, 0xef]);
2967
2968            Ok(())
2969        }
2970
2971        /// Test unified H265Depacketizer handling all packet types.
2972        /// Verifies depacketizer correctly routes Single NAL, FU, AP, and PACI packets.
2973        #[test]
2974        fn test_h265_packet() -> Result<()> {
2975            #[derive(Default)]
2976            struct TestType {
2977                raw: &'static [u8],
2978                with_donl: bool,
2979                expected_packet_type: Option<H265Payload>,
2980                expected_err: Option<PacketError>,
2981            }
2982            let tests = vec![
2983                TestType {
2984                    raw: &[],
2985                    expected_err: Some(PacketError::ErrShortPacket),
2986                    ..Default::default()
2987                },
2988                TestType {
2989                    raw: &[0x62, 0x01, 0x93],
2990                    expected_err: Some(PacketError::ErrShortPacket),
2991                    ..Default::default()
2992                },
2993                TestType {
2994                    raw: &[0x64, 0x01, 0x93, 0xaf],
2995                    expected_err: Some(PacketError::ErrShortPacket),
2996                    ..Default::default()
2997                },
2998                TestType {
2999                    raw: &[0x01, 0x01],
3000                    with_donl: true,
3001                    expected_err: Some(PacketError::ErrShortPacket),
3002                    ..Default::default()
3003                },
3004                // FBit enabled in H265NALUHeader
3005                TestType {
3006                    raw: &[0x80, 0x01, 0x93, 0xaf, 0xaf, 0xaf, 0xaf],
3007                    expected_err: Some(PacketError::ErrH265CorruptedPacket),
3008                    ..Default::default()
3009                },
3010                // Valid H265SingleNALUnitPacket
3011                TestType {
3012                    raw: &[0x01, 0x01, 0xab, 0xcd, 0xef],
3013                    expected_packet_type: Some(H265Payload::H265SingleNALUnitPacket(
3014                        H265SingleNALUnitPacket::default(),
3015                    )),
3016                    ..Default::default()
3017                },
3018                // Invalid H265SingleNALUnitPacket
3019                TestType {
3020                    raw: &[0x01, 0x01, 0x93, 0xaf],
3021                    expected_err: Some(PacketError::ErrShortPacket),
3022                    with_donl: true,
3023                    ..Default::default()
3024                },
3025                // Valid H265PACIPacket
3026                TestType {
3027                    raw: &[
3028                        0x64, 0x01, 0x64, 0b00111000, 0xaa, 0xbb, 0x80, 0xab, 0xcd, 0xef,
3029                    ],
3030                    expected_packet_type: Some(H265Payload::H265PACIPacket(
3031                        H265PACIPacket::default(),
3032                    )),
3033                    ..Default::default()
3034                },
3035                // Valid H265FragmentationUnitPacket
3036                TestType {
3037                    raw: &[0x62, 0x01, 0x93, 0xcc, 0xdd, 0xaf, 0x0d, 0x5a],
3038                    expected_packet_type: Some(H265Payload::H265FragmentationUnitPacket(
3039                        H265FragmentationUnitPacket::default(),
3040                    )),
3041                    with_donl: true,
3042                    ..Default::default()
3043                },
3044                // Valid H265AggregationPacket
3045                TestType {
3046                    raw: &[
3047                        0x60, 0x01, 0xcc, 0xdd, 0x00, 0x02, 0xff, 0xee, 0x77, 0x00, 0x01, 0xaa,
3048                    ],
3049                    expected_packet_type: Some(H265Payload::H265AggregationPacket(
3050                        H265AggregationPacket::default(),
3051                    )),
3052                    with_donl: true,
3053                    ..Default::default()
3054                },
3055                // Invalid H265AggregationPacket
3056                TestType {
3057                    raw: &[0x60, 0x01, 0x00, 0x01, 0x00, 0x02, 0x00, 0x00],
3058                    expected_err: Some(PacketError::ErrShortPacket),
3059                    with_donl: true,
3060                    ..Default::default()
3061                },
3062                // IDR Single NAL
3063                TestType {
3064                    raw: &[0x26, 0x01, 0xde, 0xad],
3065                    expected_packet_type: Some(H265Payload::H265SingleNALUnitPacket(
3066                        H265SingleNALUnitPacket::default(),
3067                    )),
3068                    ..Default::default()
3069                },
3070                // FU start of IDR_W_RADL
3071                TestType {
3072                    raw: &[0x62, 0x01, 0x93, 0xaa, 0xbb],
3073                    expected_packet_type: Some(H265Payload::H265FragmentationUnitPacket(
3074                        H265FragmentationUnitPacket::default(),
3075                    )),
3076                    ..Default::default()
3077                },
3078                // AP containing IDR (with DONL)
3079                TestType {
3080                    raw: &[
3081                        0x60, 0x01, // AP
3082                        0x00, 0x10, // DONL
3083                        0x00, 0x01, // size
3084                        0x26, // IDR header byte
3085                        0x00, // DOND
3086                        0x00, 0x01, // size
3087                        0x01, // TRAIL
3088                    ],
3089                    with_donl: true,
3090                    expected_packet_type: Some(H265Payload::H265AggregationPacket(
3091                        H265AggregationPacket::default(),
3092                    )),
3093                    ..Default::default()
3094                },
3095                // FU with S=1 and E=1 (illegal but must still be routed as FU)
3096                TestType {
3097                    raw: &[0x62, 0x01, 0xD3, 0xaa, 0xbb],
3098                    expected_packet_type: Some(H265Payload::H265FragmentationUnitPacket(
3099                        H265FragmentationUnitPacket::default(),
3100                    )),
3101                    ..Default::default()
3102                },
3103                TestType {
3104                    raw: &[
3105                        0x64, 0x01,       // PACI header
3106                        0x64,       // PHES
3107                        0b00111000, // TSCI
3108                        0x62, 0x01, // FU outer header
3109                        0x93, // S=1, FuType=19 (IDR)
3110                        0xaa, 0xbb,
3111                    ],
3112                    expected_packet_type: Some(H265Payload::H265PACIPacket(
3113                        H265PACIPacket::default(),
3114                    )),
3115                    ..Default::default()
3116                },
3117            ];
3118
3119            for cur in tests {
3120                let mut pck = H265Depacketizer::default();
3121                if cur.with_donl {
3122                    pck.with_donl(true);
3123                }
3124
3125                let mut out = Vec::new();
3126                let mut extra = CodecExtra::None;
3127                let result = pck.depacketize(&cur.raw, &mut out, &mut extra);
3128
3129                if cur.expected_err.is_some() && result.is_ok() {
3130                    assert!(false, "should error");
3131                } else if cur.expected_err.is_none() && result.is_err() {
3132                    assert!(false, "should not error");
3133                }
3134
3135                if cur.expected_err.is_some() {
3136                    continue;
3137                }
3138
3139                if let Some(expected_packet_type) = &cur.expected_packet_type {
3140                    //TODO: assert_eq!(pck.packet(), expected_packet_type, "invalid packet type");
3141                    let pck_packet = pck.payload();
3142                    match (pck_packet, expected_packet_type) {
3143                        (
3144                            &H265Payload::H265SingleNALUnitPacket(_),
3145                            &H265Payload::H265SingleNALUnitPacket(_),
3146                        ) => assert!(true),
3147                        (
3148                            &H265Payload::H265FragmentationUnitPacket(_),
3149                            &H265Payload::H265FragmentationUnitPacket(_),
3150                        ) => assert!(true),
3151                        (
3152                            &H265Payload::H265AggregationPacket(_),
3153                            &H265Payload::H265AggregationPacket(_),
3154                        ) => assert!(true),
3155                        (&H265Payload::H265PACIPacket(_), &H265Payload::H265PACIPacket(_)) => {
3156                            assert!(true)
3157                        }
3158                        _ => assert!(false),
3159                    };
3160                }
3161            }
3162
3163            Ok(())
3164        }
3165    } // end parse_tests
3166
3167    /// Tests for NAL unit → RTP payload emission.
3168    /// Validates packetization behavior: single NAL, FU fragmentation, AP aggregation.
3169    mod emit_tests {
3170        use super::*;
3171
3172        /// Test packetizer handling of small NAL units that fit in one packet.
3173        /// Verifies single NAL units are passed through unchanged.
3174        #[test]
3175        fn test_h265_packetizer_single_nalu() -> Result<()> {
3176            let mut p = H265Packetizer::default();
3177
3178            // A minimal "single NAL" (2-byte NAL header + payload).
3179            // Use a non-parameter-set type so the packetizer doesn't cache it.
3180            let nalu = b"\x02\x01\xaa\xbb\xcc".to_vec();
3181
3182            let out = p.packetize(1200, &nalu)?;
3183            assert_eq!(out.len(), 1);
3184            assert_eq!(out[0], nalu);
3185
3186            Ok(())
3187        }
3188
3189        /// Test packetizer splitting Annex-B byte stream into individual NAL units.
3190        /// Verifies correct parsing of 00 00 01 and 00 00 00 01 start codes.
3191        #[test]
3192        fn test_h265_packetizer_annexb_split() -> Result<()> {
3193            let mut p = H265Packetizer::default();
3194
3195            // Use non-parameter-set NALU types so they are emitted directly.
3196            let nalu1 = b"\x02\x01\x11\x22\x33".to_vec();
3197            let nalu2 = b"\x26\x01\xaa\xbb\xcc\xdd".to_vec();
3198
3199            // Annex-B start codes around the NAL units.
3200            let mut bytestream = Vec::new();
3201            bytestream.extend_from_slice(&[0x00, 0x00, 0x00, 0x01]);
3202            bytestream.extend_from_slice(&nalu1);
3203            bytestream.extend_from_slice(&[0x00, 0x00, 0x01]);
3204            bytestream.extend_from_slice(&nalu2);
3205
3206            let out = p.packetize(1200, &bytestream)?;
3207            assert_eq!(out.len(), 2);
3208            assert_eq!(out[0], nalu1);
3209            assert_eq!(out[1], nalu2);
3210
3211            Ok(())
3212        }
3213
3214        /// Test packetizer dropping AUD NAL units and keeping filler NAL units.
3215        #[test]
3216        fn test_h265_packetizer_drops_aud_keeps_filler() -> Result<()> {
3217            let mut p = H265Packetizer::default();
3218
3219            // AUD (type 35), non-parameter-set NALU, filler (type 38).
3220            let aud = b"\x46\x01\x50".to_vec();
3221            let nalu = b"\x02\x01\x11\x22\x33".to_vec();
3222            let fd = b"\x4c\x01\xff\xff\x80".to_vec();
3223
3224            let mut bytestream = Vec::new();
3225            for n in [&aud, &nalu, &fd] {
3226                bytestream.extend_from_slice(&[0x00, 0x00, 0x00, 0x01]);
3227                bytestream.extend_from_slice(n);
3228            }
3229
3230            let out = p.packetize(1200, &bytestream)?;
3231            assert_eq!(out.len(), 2);
3232            assert_eq!(out[0], nalu);
3233            assert_eq!(out[1], fd);
3234
3235            Ok(())
3236        }
3237
3238        /// Test FU fragmentation preserves NAL unit payload exactly.
3239        /// Verifies fragmented packets can be reassembled to original payload without corruption.
3240        #[test]
3241        fn test_h265_packetizer_fu_fragmentation_roundtrip_payload() -> Result<()> {
3242            let mut p = H265Packetizer::default();
3243
3244            // Craft a NAL unit large enough to force FU fragmentation.
3245            // Header 0x02 0x01 => F=0, type=1 (VCL), tid=1.
3246            let mut nalu = vec![0x02, 0x01];
3247            nalu.extend((0..60).map(|i| i as u8));
3248
3249            // Force fragmentation: FU overhead is 3 bytes, so this yields multiple fragments.
3250            let mtu = 20;
3251            let out = p.packetize(mtu, &nalu)?;
3252            assert!(out.len() > 1, "expected fragmentation");
3253
3254            // Validate each FU packet and reconstruct the original payload (sans 2-byte NAL header).
3255            let orig_hdr = H265NALUHeader::new(nalu[0], nalu[1]);
3256            let orig_type = orig_hdr.nalu_type();
3257            let orig_payload = &nalu[H265NALU_HEADER_SIZE..];
3258
3259            let mut reconstructed = Vec::new();
3260
3261            for (idx, pkt) in out.iter().enumerate() {
3262                assert!(pkt.len() <= mtu);
3263                assert!(pkt.len() >= H265NALU_HEADER_SIZE + H265FRAGMENTATION_UNIT_HEADER_SIZE);
3264
3265                let hdr = H265NALUHeader::new(pkt[0], pkt[1]);
3266                assert_eq!(hdr.nalu_type(), H265NALU_FRAGMENTATION_UNIT_TYPE);
3267                assert!(!hdr.f());
3268                assert_eq!(hdr.layer_id(), orig_hdr.layer_id());
3269                assert_eq!(hdr.tid(), orig_hdr.tid());
3270
3271                let fu = H265FragmentationUnitHeader(pkt[2]);
3272                assert_eq!(fu.fu_type(), orig_type);
3273                if idx == 0 {
3274                    assert!(fu.s());
3275                    assert!(!fu.e());
3276                } else if idx == out.len() - 1 {
3277                    assert!(!fu.s());
3278                    assert!(fu.e());
3279                } else {
3280                    assert!(!fu.s());
3281                    assert!(!fu.e());
3282                }
3283
3284                reconstructed.extend_from_slice(&pkt[3..]);
3285            }
3286
3287            assert_eq!(reconstructed, orig_payload);
3288
3289            Ok(())
3290        }
3291
3292        /// Test packetizer does not fragment small NAL units.
3293        /// Verifies NAL units smaller than MTU are emitted as single packets.
3294        #[test]
3295        fn test_h265_packetizer_single_nalu_no_fragment() -> Result<()> {
3296            let mut p = H265Packetizer::default();
3297
3298            // A small NALU: 2-byte header + payload.
3299            let nalu = [0x02, 0x01, 0xaa, 0xbb, 0xcc, 0xdd];
3300            let pkts = p.packetize(1200, &nalu)?;
3301
3302            assert_eq!(pkts.len(), 1);
3303            assert_eq!(pkts[0], nalu);
3304            Ok(())
3305        }
3306
3307        /// Test packetizer correctly splits multiple NAL units from Annex-B stream.
3308        /// Verifies each NAL unit is extracted and emitted separately.
3309        #[test]
3310        fn test_h265_packetizer_annexb_splits_nalus() -> Result<()> {
3311            let mut p = H265Packetizer::default();
3312
3313            // Use non-parameter-set NALU types so they are emitted directly.
3314            let nalu1 = [0x02, 0x01, 0x11, 0x22, 0x33];
3315            let nalu2 = [0x26, 0x01, 0x44, 0x55];
3316
3317            let mut annexb = Vec::new();
3318            annexb.extend_from_slice(&[0x00, 0x00, 0x01]);
3319            annexb.extend_from_slice(&nalu1);
3320            annexb.extend_from_slice(&[0x00, 0x00, 0x00, 0x01]);
3321            annexb.extend_from_slice(&nalu2);
3322
3323            let pkts = p.packetize(1200, &annexb)?;
3324
3325            assert_eq!(pkts.len(), 2);
3326            assert_eq!(pkts[0], nalu1);
3327            assert_eq!(pkts[1], nalu2);
3328            Ok(())
3329        }
3330
3331        /// Test packetizer aggregates VPS/SPS/PPS parameter sets into AP packet.
3332        /// Verifies parameter sets are cached and emitted together before first VCL NAL.
3333        #[test]
3334        fn test_h265_packetizer_emits_ap_for_vps_sps_pps() -> Result<()> {
3335            let mut p = H265Packetizer::default();
3336
3337            // VPS (type 32), SPS (type 33), PPS (type 34), then a VCL NALU (type 1).
3338            let vps = vec![0x40, 0x01, 0x01, 0x02];
3339            let sps = vec![0x42, 0x01, 0x03, 0x04, 0x05];
3340            let pps = vec![0x44, 0x01, 0x06];
3341            let vcl = vec![0x02, 0x01, 0xaa, 0xbb, 0xcc, 0xdd];
3342
3343            // Cache parameter sets (no output yet).
3344            assert!(p.packetize(1200, &vps)?.is_empty());
3345            assert!(p.packetize(1200, &sps)?.is_empty());
3346            assert!(p.packetize(1200, &pps)?.is_empty());
3347
3348            // First non-parameter-set NALU should trigger AP emission.
3349            let out = p.packetize(1200, &vcl)?;
3350            assert_eq!(out.len(), 2);
3351
3352            // Validate AP packet structure.
3353            assert!(out[0].len() >= H265NALU_HEADER_SIZE + 2);
3354            let ap_hdr = H265NALUHeader::new(out[0][0], out[0][1]);
3355            assert_eq!(ap_hdr.nalu_type(), H265NALU_AGGREGATION_PACKET_TYPE);
3356
3357            let mut off = H265NALU_HEADER_SIZE;
3358            for expected in [&vps, &sps, &pps] {
3359                let len = u16::from_be_bytes([out[0][off], out[0][off + 1]]) as usize;
3360                off += 2;
3361                assert_eq!(len, expected.len());
3362                assert_eq!(&out[0][off..off + len], expected.as_slice());
3363                off += len;
3364            }
3365
3366            // And the actual VCL NALU follows as a normal single-NALU packet.
3367            assert_eq!(out[1], vcl);
3368
3369            Ok(())
3370        }
3371
3372        /// Test packetizer falls back to individual packets when AP exceeds MTU.
3373        /// Verifies parameter sets are sent separately if aggregation would violate MTU limit.
3374        #[test]
3375        fn test_h265_packetizer_ap_exceeds_mtu_fallback() -> Result<()> {
3376            let mut p = H265Packetizer::default();
3377
3378            // Create VPS, SPS, PPS parameter sets.
3379            let vps = vec![0x40, 0x01, 0x01, 0x02];
3380            let sps = vec![0x42, 0x01, 0x03, 0x04, 0x05];
3381            let pps = vec![0x44, 0x01, 0x06];
3382            let vcl = vec![0x02, 0x01, 0xaa, 0xbb];
3383
3384            // Cache parameter sets (no output yet).
3385            assert!(p.packetize(1200, &vps)?.is_empty());
3386            assert!(p.packetize(1200, &sps)?.is_empty());
3387            assert!(p.packetize(1200, &pps)?.is_empty());
3388
3389            // Set MTU to a value smaller than the AP size would be.
3390            // AP overhead: 2 (AP header) + 2 (VPS size) + 4 (VPS) + 2 (SPS size)
3391            //              + 5 (SPS) + 2 (PPS size) + 3 (PPS) = 20 bytes
3392            // So MTU=15 will be too small for the AP.
3393            let small_mtu = 15;
3394            let out = p.packetize(small_mtu, &vcl)?;
3395
3396            // Should emit parameter sets as individual Single NAL packets, then the VCL NALU.
3397            // Expected: VPS, SPS, PPS, VCL = 4 packets
3398            assert_eq!(
3399                out.len(),
3400                4,
3401                "Expected 4 packets (VPS, SPS, PPS, VCL) when AP exceeds MTU"
3402            );
3403
3404            // Verify each parameter set packet.
3405            assert_eq!(out[0], vps, "First packet should be VPS");
3406            assert_eq!(out[1], sps, "Second packet should be SPS");
3407            assert_eq!(out[2], pps, "Third packet should be PPS");
3408            assert_eq!(out[3], vcl, "Fourth packet should be VCL");
3409
3410            Ok(())
3411        }
3412
3413        /// Test full round-trip of packetizer + depacketizer for fragmented NAL units.
3414        /// Verifies FU packets are correctly created and reassembled to Annex-B format.
3415        #[test]
3416        fn test_h265_fu_roundtrip_with_depacketizer() -> Result<()> {
3417            let mut packetizer = H265Packetizer::default();
3418            let mut depacketizer = H265Depacketizer::default();
3419
3420            // Create a large NAL unit that will be fragmented.
3421            // Type 1 (TRAIL_R), layer_id=0, tid=1
3422            let mut original_nalu = vec![0x02, 0x01];
3423            original_nalu.extend((0..200).map(|i| (i % 256) as u8));
3424
3425            // Force fragmentation with small MTU
3426            let mtu = 50;
3427            let packets = packetizer.packetize(mtu, &original_nalu)?;
3428
3429            // Verify fragmentation occurred
3430            assert!(packets.len() > 1, "Expected multiple FU packets");
3431            assert!(
3432                packets.iter().all(|p| p.len() <= mtu),
3433                "All packets should fit MTU"
3434            );
3435
3436            // Depacketize each FU packet - they should accumulate in the depacketizer
3437            let mut output = Vec::new();
3438            let mut extra = CodecExtra::None;
3439
3440            for (i, packet) in packets.iter().enumerate() {
3441                output.clear();
3442                extra = CodecExtra::None;
3443
3444                let result = depacketizer.depacketize(packet, &mut output, &mut extra);
3445
3446                // Only the last fragment should produce output
3447                if i < packets.len() - 1 {
3448                    assert!(result.is_ok());
3449                    assert!(
3450                        output.is_empty(),
3451                        "Intermediate FU fragments should not produce output"
3452                    );
3453                } else {
3454                    assert!(result.is_ok());
3455                    assert!(
3456                        !output.is_empty(),
3457                        "Final FU fragment should produce output"
3458                    );
3459                    // Output should be the complete original NAL unit in Annex-B format
3460                    // Depacketizer prepends start code
3461                    let expected_output = {
3462                        let mut tmp = Vec::from(ANNEXB_NALUSTART_CODE);
3463                        tmp.extend_from_slice(&original_nalu);
3464                        tmp
3465                    };
3466                    assert_eq!(
3467                        output, expected_output,
3468                        "Depacketized NAL unit should match original with start code"
3469                    );
3470                }
3471            }
3472
3473            Ok(())
3474        }
3475
3476        /// Test full round-trip of packetizer + depacketizer for aggregation packets.
3477        /// Verifies AP packets are correctly created and depacketized to Annex-B format.
3478        #[test]
3479        fn test_h265_ap_roundtrip_with_depacketizer() -> Result<()> {
3480            let mut packetizer = H265Packetizer::default();
3481            let mut depacketizer = H265Depacketizer::default();
3482
3483            // Create VPS, SPS, PPS parameter sets and a VCL NAL unit
3484            let vps = vec![0x40, 0x01, 0xaa, 0xbb, 0xcc];
3485            let sps = vec![0x42, 0x01, 0xdd, 0xee, 0xff, 0x11, 0x22];
3486            let pps = vec![0x44, 0x01, 0x33, 0x44];
3487            let vcl = vec![0x26, 0x01, 0x55, 0x66, 0x77, 0x88]; // IDR_W_RADL
3488
3489            // Cache parameter sets (no output yet)
3490            assert!(packetizer.packetize(1200, &vps)?.is_empty());
3491            assert!(packetizer.packetize(1200, &sps)?.is_empty());
3492            assert!(packetizer.packetize(1200, &pps)?.is_empty());
3493
3494            // Emit AP + VCL
3495            let packets = packetizer.packetize(1200, &vcl)?;
3496            assert_eq!(packets.len(), 2, "Expected AP packet + VCL packet");
3497
3498            // Depacketize the AP packet
3499            let mut output = Vec::new();
3500            let mut extra = CodecExtra::None;
3501
3502            depacketizer.depacketize(&packets[0], &mut output, &mut extra)?;
3503
3504            // AP depacketization produces Annex-B format with start codes before each NAL
3505            let mut offset = 0;
3506
3507            // Check VPS (with start code)
3508            assert_eq!(&output[offset..offset + 4], ANNEXB_NALUSTART_CODE);
3509            offset += 4;
3510            assert_eq!(
3511                &output[offset..offset + vps.len()],
3512                &vps[..],
3513                "VPS should match"
3514            );
3515            offset += vps.len();
3516
3517            // Check SPS (with start code)
3518            assert_eq!(&output[offset..offset + 4], ANNEXB_NALUSTART_CODE);
3519            offset += 4;
3520            assert_eq!(
3521                &output[offset..offset + sps.len()],
3522                &sps[..],
3523                "SPS should match"
3524            );
3525            offset += sps.len();
3526
3527            // Check PPS (with start code)
3528            assert_eq!(&output[offset..offset + 4], ANNEXB_NALUSTART_CODE);
3529            offset += 4;
3530            assert_eq!(
3531                &output[offset..offset + pps.len()],
3532                &pps[..],
3533                "PPS should match"
3534            );
3535            offset += pps.len();
3536
3537            assert_eq!(offset, output.len(), "All AP payload should be consumed");
3538
3539            // Depacketize the VCL packet (also with start code)
3540            output.clear();
3541            extra = CodecExtra::None;
3542            depacketizer.depacketize(&packets[1], &mut output, &mut extra)?;
3543            let expected_vcl = {
3544                let mut tmp = Vec::from(ANNEXB_NALUSTART_CODE);
3545                tmp.extend_from_slice(&vcl);
3546                tmp
3547            };
3548            assert_eq!(
3549                output, expected_vcl,
3550                "VCL NAL unit should match original with start code"
3551            );
3552
3553            Ok(())
3554        }
3555
3556        /// Test full round-trip of packetizer + depacketizer for single NAL units.
3557        /// Verifies small NAL units pass through correctly and are converted to Annex-B format.
3558        #[test]
3559        fn test_h265_single_nalu_roundtrip_with_depacketizer() -> Result<()> {
3560            let mut packetizer = H265Packetizer::default();
3561            let mut depacketizer = H265Depacketizer::default();
3562
3563            // Create a small NAL unit that won't be fragmented
3564            let original_nalu = vec![0x02, 0x01, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff];
3565
3566            // Packetize with large MTU (no fragmentation)
3567            let packets = packetizer.packetize(1200, &original_nalu)?;
3568            assert_eq!(packets.len(), 1, "Expected single packet");
3569            assert_eq!(
3570                packets[0], original_nalu,
3571                "Single NAL packet should be unchanged"
3572            );
3573
3574            // Depacketize (output will have Annex-B start code)
3575            let mut output = Vec::new();
3576            let mut extra = CodecExtra::None;
3577            depacketizer.depacketize(&packets[0], &mut output, &mut extra)?;
3578
3579            let expected_output = {
3580                let mut tmp = Vec::from(ANNEXB_NALUSTART_CODE);
3581                tmp.extend_from_slice(&original_nalu);
3582                tmp
3583            };
3584            assert_eq!(
3585                output, expected_output,
3586                "Depacketized NAL unit should match original with start code"
3587            );
3588
3589            Ok(())
3590        }
3591
3592        /// Test realistic sequence with multiple packet types (AP + single NAL + FU).
3593        /// Verifies packetizer/depacketizer handle mixed packet types in one stream.
3594        #[test]
3595        fn test_h265_mixed_packet_types_roundtrip() -> Result<()> {
3596            let mut packetizer = H265Packetizer::default();
3597            let mut depacketizer = H265Depacketizer::default();
3598
3599            // Test a realistic sequence: VPS, SPS, PPS, small VCL, large VCL
3600            let vps = vec![0x40, 0x01, 0x01, 0x02, 0x03];
3601            let sps = vec![0x42, 0x01, 0x04, 0x05, 0x06, 0x07];
3602            let pps = vec![0x44, 0x01, 0x08, 0x09];
3603            let small_vcl = vec![0x02, 0x01, 0x0a, 0x0b, 0x0c];
3604
3605            // Large VCL that will be fragmented
3606            let mut large_vcl = vec![0x26, 0x01]; // IDR_W_RADL
3607            large_vcl.extend((0..150).map(|i| (i % 256) as u8));
3608
3609            // Cache parameter sets
3610            assert!(packetizer.packetize(1200, &vps)?.is_empty());
3611            assert!(packetizer.packetize(1200, &sps)?.is_empty());
3612            assert!(packetizer.packetize(1200, &pps)?.is_empty());
3613
3614            // First VCL triggers AP emission
3615            let packets1 = packetizer.packetize(1200, &small_vcl)?;
3616            assert_eq!(packets1.len(), 2, "Expected AP + small VCL");
3617
3618            // Verify AP depacketization (Annex-B format with start codes)
3619            let mut output = Vec::new();
3620            let mut extra = CodecExtra::None;
3621            depacketizer.depacketize(&packets1[0], &mut output, &mut extra)?;
3622
3623            let mut offset = 0;
3624            // VPS with start code
3625            assert_eq!(&output[offset..offset + 4], ANNEXB_NALUSTART_CODE);
3626            offset += 4;
3627            assert_eq!(&output[offset..offset + vps.len()], &vps[..]);
3628            offset += vps.len();
3629            // SPS with start code
3630            assert_eq!(&output[offset..offset + 4], ANNEXB_NALUSTART_CODE);
3631            offset += 4;
3632            assert_eq!(&output[offset..offset + sps.len()], &sps[..]);
3633            offset += sps.len();
3634            // PPS with start code
3635            assert_eq!(&output[offset..offset + 4], ANNEXB_NALUSTART_CODE);
3636            offset += 4;
3637            assert_eq!(&output[offset..offset + pps.len()], &pps[..]);
3638
3639            // Verify small VCL (with start code)
3640            output.clear();
3641            depacketizer.depacketize(&packets1[1], &mut output, &mut extra)?;
3642            let expected_small_vcl = {
3643                let mut tmp = Vec::from(ANNEXB_NALUSTART_CODE);
3644                tmp.extend_from_slice(&small_vcl);
3645                tmp
3646            };
3647            assert_eq!(output, expected_small_vcl);
3648
3649            // Large VCL should be fragmented
3650            let packets2 = packetizer.packetize(60, &large_vcl)?;
3651            assert!(packets2.len() > 1, "Large VCL should be fragmented");
3652
3653            // Depacketize FU packets
3654            for (i, packet) in packets2.iter().enumerate() {
3655                output.clear();
3656                depacketizer.depacketize(packet, &mut output, &mut extra)?;
3657
3658                if i < packets2.len() - 1 {
3659                    assert!(
3660                        output.is_empty(),
3661                        "Intermediate fragments shouldn't produce output"
3662                    );
3663                } else {
3664                    // Final fragment produces Annex-B output
3665                    let expected_large_vcl = {
3666                        let mut tmp = Vec::from(ANNEXB_NALUSTART_CODE);
3667                        tmp.extend_from_slice(&large_vcl);
3668                        tmp
3669                    };
3670                    assert_eq!(
3671                        output, expected_large_vcl,
3672                        "Final fragment should produce complete NAL with start code"
3673                    );
3674                }
3675            }
3676
3677            Ok(())
3678        }
3679
3680        /// Test Annex-B input stream through packetizer and depacketizer.
3681        /// Verifies complete round-trip preserves NAL units from Annex-B to RTP to Annex-B.
3682        #[test]
3683        fn test_h265_annexb_roundtrip_with_depacketizer() -> Result<()> {
3684            let mut packetizer = H265Packetizer::default();
3685            let mut depacketizer = H265Depacketizer::default();
3686
3687            // Create Annex-B formatted input with multiple NAL units
3688            let nalu1 = vec![0x40, 0x01, 0xaa, 0xbb]; // VPS
3689            let nalu2 = vec![0x42, 0x01, 0xcc, 0xdd, 0xee]; // SPS
3690            let nalu3 = vec![0x44, 0x01, 0xff]; // PPS
3691            let nalu4 = vec![0x02, 0x01, 0x11, 0x22, 0x33]; // VCL
3692
3693            // Build Annex-B bytestream
3694            let mut annexb = Vec::new();
3695            annexb.extend_from_slice(ANNEXB_NALUSTART_CODE);
3696            annexb.extend_from_slice(&nalu1);
3697            annexb.extend_from_slice(ANNEXB_NALUSTART_CODE);
3698            annexb.extend_from_slice(&nalu2);
3699            annexb.extend_from_slice(ANNEXB_NALUSTART_CODE);
3700            annexb.extend_from_slice(&nalu3);
3701            annexb.extend_from_slice(ANNEXB_NALUSTART_CODE);
3702            annexb.extend_from_slice(&nalu4);
3703
3704            // Packetize the Annex-B stream
3705            let packets = packetizer.packetize(1200, &annexb)?;
3706
3707            // Should get AP (with VPS/SPS/PPS) + VCL
3708            assert_eq!(packets.len(), 2, "Expected AP + VCL from Annex-B stream");
3709
3710            // Depacketize and verify (output is Annex-B format)
3711            let mut output = Vec::new();
3712            let mut extra = CodecExtra::None;
3713
3714            // AP packet produces start code before each NAL
3715            depacketizer.depacketize(&packets[0], &mut output, &mut extra)?;
3716            let mut offset = 0;
3717            // VPS
3718            assert_eq!(&output[offset..offset + 4], ANNEXB_NALUSTART_CODE);
3719            offset += 4;
3720            assert_eq!(&output[offset..offset + nalu1.len()], &nalu1[..]);
3721            offset += nalu1.len();
3722            // SPS
3723            assert_eq!(&output[offset..offset + 4], ANNEXB_NALUSTART_CODE);
3724            offset += 4;
3725            assert_eq!(&output[offset..offset + nalu2.len()], &nalu2[..]);
3726            offset += nalu2.len();
3727            // PPS
3728            assert_eq!(&output[offset..offset + 4], ANNEXB_NALUSTART_CODE);
3729            offset += 4;
3730            assert_eq!(&output[offset..offset + nalu3.len()], &nalu3[..]);
3731
3732            // VCL packet (with start code)
3733            output.clear();
3734            depacketizer.depacketize(&packets[1], &mut output, &mut extra)?;
3735            let expected_nalu4 = {
3736                let mut tmp = Vec::from(ANNEXB_NALUSTART_CODE);
3737                tmp.extend_from_slice(&nalu4);
3738                tmp
3739            };
3740            assert_eq!(output, expected_nalu4);
3741
3742            Ok(())
3743        }
3744
3745        /// Test packetizer respects various MTU sizes during fragmentation.
3746        /// Verifies all output packets fit within specified MTU limits.
3747        #[test]
3748        fn test_h265_mtu_variation() -> Result<()> {
3749            // Test fragmentation at various MTU sizes to ensure correct packet splitting
3750            let mut packetizer = H265Packetizer::default();
3751
3752            // Create a 2000-byte NAL unit
3753            let mut large_nalu = vec![0x26, 0x01]; // NALU header (type 19 - IDR)
3754            for i in 0..1998 {
3755                large_nalu.push((i % 256) as u8);
3756            }
3757
3758            // Test various MTU sizes
3759            let mtu_sizes = [100, 200, 500, 1000, MAX_PACKET_SIZE];
3760
3761            for mtu in mtu_sizes {
3762                let packets = packetizer.packetize(mtu, &large_nalu)?;
3763
3764                // Verify all packets fit within MTU
3765                for packet in &packets {
3766                    assert!(
3767                        packet.len() <= mtu,
3768                        "Packet size {} exceeds MTU {} for MTU test",
3769                        packet.len(),
3770                        mtu
3771                    );
3772                }
3773
3774                // Verify all packets are FU packets (type 49)
3775                for packet in &packets {
3776                    let header = H265NALUHeader::new(packet[0], packet[1]);
3777                    assert_eq!(
3778                        header.nalu_type(),
3779                        H265NALU_FRAGMENTATION_UNIT_TYPE,
3780                        "Expected FU packet type for MTU {}",
3781                        mtu
3782                    );
3783                }
3784
3785                // Verify at least one packet was created
3786                assert!(
3787                    !packets.is_empty(),
3788                    "Expected at least one packet for MTU {}",
3789                    mtu
3790                );
3791            }
3792
3793            Ok(())
3794        }
3795
3796        /// Test FU packet S (start) and E (end) flags are set correctly.
3797        /// Verifies first packet has S=1, middle have S=0 E=0, last has E=1.
3798        #[test]
3799        fn test_h265_fragmentation_start_end_flags() -> Result<()> {
3800            // Explicitly test S (start) and E (end) flags in FU headers
3801            let mut packetizer = H265Packetizer::default();
3802
3803            // Create a NAL unit that will require fragmentation
3804            let mut large_nalu = vec![0x26, 0x01]; // IDR NAL header
3805            large_nalu.extend(vec![0xff; 200]); // 202 bytes total
3806
3807            let packets = packetizer.packetize(100, &large_nalu)?;
3808
3809            assert!(
3810                packets.len() >= 2,
3811                "Expected fragmentation into multiple packets"
3812            );
3813
3814            // First packet should have S flag set
3815            let first_fu_header = H265FragmentationUnitHeader(packets[0][2]);
3816            assert!(
3817                first_fu_header.s(),
3818                "First FU packet should have S flag set"
3819            );
3820            assert!(
3821                !first_fu_header.e(),
3822                "First FU packet should not have E flag set"
3823            );
3824
3825            // Middle packets (if any) should have neither S nor E
3826            for i in 1..packets.len() - 1 {
3827                let mid_fu_header = H265FragmentationUnitHeader(packets[i][2]);
3828                assert!(
3829                    !mid_fu_header.s(),
3830                    "Middle FU packet should not have S flag set"
3831                );
3832                assert!(
3833                    !mid_fu_header.e(),
3834                    "Middle FU packet should not have E flag set"
3835                );
3836            }
3837
3838            // Last packet should have E flag set
3839            let last_fu_header = H265FragmentationUnitHeader(packets[packets.len() - 1][2]);
3840            assert!(
3841                !last_fu_header.s(),
3842                "Last FU packet should not have S flag set"
3843            );
3844            assert!(last_fu_header.e(), "Last FU packet should have E flag set");
3845
3846            // All fragments should preserve the original NAL unit type
3847            let original_type = 19; // IDR type
3848            for packet in &packets {
3849                let fu_header = H265FragmentationUnitHeader(packet[2]);
3850                assert_eq!(
3851                    fu_header.fu_type(),
3852                    original_type,
3853                    "FU header should preserve original NAL type"
3854                );
3855            }
3856
3857            Ok(())
3858        }
3859
3860        /// Test partition head detection for RTP packet reassembly.
3861        /// Verifies single NAL, FU start, and AP packets are identified as partition heads.
3862        #[test]
3863        fn test_h265_is_partition_head() -> Result<()> {
3864            let depacketizer = H265Depacketizer::default();
3865
3866            // Nil/empty should not be partition head
3867            assert!(
3868                !depacketizer.is_partition_head(&[]),
3869                "Empty packet should not be partition head"
3870            );
3871
3872            // Single NAL unit should be partition head
3873            let single_nalu = vec![0x02, 0x01, 0xab, 0xcd, 0xef];
3874            assert!(
3875                depacketizer.is_partition_head(&single_nalu),
3876                "Single NAL unit should be partition head"
3877            );
3878
3879            // Packet with F bit set should be partition head
3880            let fbit_nalu = vec![0x80, 0x00, 0x00];
3881            assert!(
3882                depacketizer.is_partition_head(&fbit_nalu),
3883                "F-bit NAL unit should be partition head"
3884            );
3885
3886            // FU start packet (S=1) should be partition head
3887            let fu_start = vec![
3888                0x62, 0x01, // FU indicator (type 49)
3889                0x93, // FU header: S=1, E=0, type=19
3890            ];
3891            assert!(
3892                depacketizer.is_partition_head(&fu_start),
3893                "FU start packet should be partition head"
3894            );
3895
3896            // FU middle packet (S=0, E=0) should NOT be partition head
3897            let fu_middle = vec![
3898                0x62, 0x01, // FU indicator (type 49)
3899                0x13, // FU header: S=0, E=0, type=19
3900            ];
3901            assert!(
3902                !depacketizer.is_partition_head(&fu_middle),
3903                "FU middle packet should not be partition head"
3904            );
3905
3906            // FU end packet (S=0, E=1) should NOT be partition head
3907            let fu_end = vec![
3908                0x62, 0x01, // FU indicator (type 49)
3909                0x53, // FU header: S=0, E=1, type=19
3910            ];
3911            assert!(
3912                !depacketizer.is_partition_head(&fu_end),
3913                "FU end packet should not be partition head"
3914            );
3915
3916            // Aggregation packet should be partition head
3917            let ap_packet = vec![
3918                0x60, 0x01, // AP indicator (type 48)
3919                0x00, 0x04, // First NAL size
3920                0x40, 0x01, 0xaa, 0xbb, // VPS
3921            ];
3922            assert!(
3923                depacketizer.is_partition_head(&ap_packet),
3924                "Aggregation packet should be partition head"
3925            );
3926
3927            Ok(())
3928        }
3929
3930        /// Test partition tail detection for RTP packet reassembly.
3931        /// Verifies FU end packets and single NAL with marker are identified as partition tails.
3932        #[test]
3933        fn test_h265_is_partition_tail() -> Result<()> {
3934            let depacketizer = H265Depacketizer::default();
3935
3936            // Nil/empty should not be partition tail
3937            assert!(
3938                !depacketizer.is_partition_tail(false, &[]),
3939                "Empty packet should not be partition tail"
3940            );
3941
3942            // Single NAL unit without marker should NOT be partition tail
3943            let single_nalu = vec![0x02, 0x01, 0xab, 0xcd, 0xef];
3944            assert!(
3945                !depacketizer.is_partition_tail(false, &single_nalu),
3946                "Single NAL unit without marker should not be partition tail"
3947            );
3948
3949            // Single NAL unit WITH marker should be partition tail
3950            assert!(
3951                depacketizer.is_partition_tail(true, &single_nalu),
3952                "Single NAL unit with marker should be partition tail"
3953            );
3954
3955            // F-bit packet without marker should NOT be partition tail
3956            let fbit_nalu = vec![0x80, 0x00, 0x00];
3957            assert!(
3958                !depacketizer.is_partition_tail(false, &fbit_nalu),
3959                "F-bit NAL unit without marker should not be partition tail"
3960            );
3961
3962            // FU start packet should NOT be partition tail
3963            let fu_start = vec![
3964                0x62, 0x01, // FU indicator (type 49)
3965                0x93, // FU header: S=1, E=0, type=19
3966            ];
3967            assert!(
3968                !depacketizer.is_partition_tail(false, &fu_start),
3969                "FU start packet should not be partition tail"
3970            );
3971
3972            // FU middle packet should NOT be partition tail
3973            let fu_middle = vec![
3974                0x62, 0x01, // FU indicator (type 49)
3975                0x13, // FU header: S=0, E=0, type=19
3976            ];
3977            assert!(
3978                !depacketizer.is_partition_tail(false, &fu_middle),
3979                "FU middle packet should not be partition tail"
3980            );
3981
3982            // FU end packet (E=1) should be partition tail
3983            let fu_end = vec![
3984                0x62, 0x01, // FU indicator (type 49)
3985                0x53, // FU header: S=0, E=1, type=19
3986            ];
3987            assert!(
3988                depacketizer.is_partition_tail(false, &fu_end),
3989                "FU end packet should be partition tail"
3990            );
3991
3992            // Aggregation packet with marker should be partition tail
3993            let ap_packet = vec![
3994                0x60, 0x01, // AP indicator (type 48)
3995                0x00, 0x04, // First NAL size
3996                0x40, 0x01, 0xaa, 0xbb, // VPS
3997            ];
3998            assert!(
3999                depacketizer.is_partition_tail(true, &ap_packet),
4000                "Aggregation packet with marker should be partition tail"
4001            );
4002
4003            Ok(())
4004        }
4005
4006        /// Test depacketization of manually constructed AP with multiple NAL units.
4007        /// Verifies AP structure with multiple aggregated units works correctly.
4008        #[test]
4009        fn test_h265_multi_nalu_aggregation() -> Result<()> {
4010            // Test aggregating multiple non-parameter-set NALUs
4011            // Note: Current implementation only aggregates VPS/SPS/PPS automatically
4012            // This test verifies the AP packet structure works for general NALUs
4013
4014            let nalu1 = vec![0x02, 0x01, 0xff, 0xff, 0xff]; // VCL NAL
4015            let nalu2 = vec![0x04, 0x01, 0xaa, 0xbb, 0xcc]; // Another VCL NAL
4016
4017            // Manually build an AP packet
4018            let mut ap_packet = vec![
4019                0x60, 0x01, // AP header (type 48)
4020            ];
4021
4022            // Add first NAL
4023            ap_packet.extend_from_slice(&(nalu1.len() as u16).to_be_bytes());
4024            ap_packet.extend_from_slice(&nalu1);
4025
4026            // Add second NAL
4027            ap_packet.extend_from_slice(&(nalu2.len() as u16).to_be_bytes());
4028            ap_packet.extend_from_slice(&nalu2);
4029
4030            // Depacketize and verify
4031            let mut depacketizer = H265Depacketizer::default();
4032            let mut output = Vec::new();
4033            let mut extra = CodecExtra::None;
4034
4035            depacketizer.depacketize(&ap_packet, &mut output, &mut extra)?;
4036
4037            // Output should contain both NALUs with Annex-B start codes
4038            let mut expected = Vec::new();
4039            expected.extend_from_slice(ANNEXB_NALUSTART_CODE);
4040            expected.extend_from_slice(&nalu1);
4041            expected.extend_from_slice(ANNEXB_NALUSTART_CODE);
4042            expected.extend_from_slice(&nalu2);
4043
4044            assert_eq!(
4045                output, expected,
4046                "Depacketized AP should contain both NALUs with start codes"
4047            );
4048
4049            Ok(())
4050        }
4051
4052        /// Test parameter set caching and AP emission on first VCL NAL.
4053        /// Verifies VPS/SPS/PPS are cached, then emitted as AP when VCL arrives.
4054        #[test]
4055        fn test_h265_packetizer_aggregation_with_marker() -> Result<()> {
4056            // Test that packetizer creates proper aggregation packets
4057            let mut packetizer = H265Packetizer::default();
4058
4059            // Build Annex-B stream with VPS + SPS + PPS
4060            let vps = vec![0x40, 0x01, 0xaa, 0xbb];
4061            let sps = vec![0x42, 0x01, 0xcc, 0xdd, 0xee];
4062            let pps = vec![0x44, 0x01, 0xff];
4063
4064            let mut annexb = Vec::new();
4065            annexb.extend_from_slice(ANNEXB_NALUSTART_CODE);
4066            annexb.extend_from_slice(&vps);
4067            annexb.extend_from_slice(ANNEXB_NALUSTART_CODE);
4068            annexb.extend_from_slice(&sps);
4069            annexb.extend_from_slice(ANNEXB_NALUSTART_CODE);
4070            annexb.extend_from_slice(&pps);
4071
4072            let packets = packetizer.packetize(MAX_PACKET_SIZE, &annexb)?;
4073
4074            // Should produce 0 packets (just caching parameter sets)
4075            assert_eq!(
4076                packets.len(),
4077                0,
4078                "Parameter sets should be cached, not emitted immediately"
4079            );
4080
4081            // Now send a VCL NAL to trigger AP emission
4082            let mut vcl_annexb = Vec::new();
4083            vcl_annexb.extend_from_slice(ANNEXB_NALUSTART_CODE);
4084            vcl_annexb.extend_from_slice(&[0x02, 0x01, 0x11, 0x22]);
4085
4086            let vcl_packets = packetizer.packetize(MAX_PACKET_SIZE, &vcl_annexb)?;
4087
4088            // Should get AP + VCL
4089            assert_eq!(
4090                vcl_packets.len(),
4091                2,
4092                "Expected AP with parameter sets + VCL packet"
4093            );
4094
4095            // First packet should be AP (type 48)
4096            let ap_header = H265NALUHeader::new(vcl_packets[0][0], vcl_packets[0][1]);
4097            assert_eq!(
4098                ap_header.nalu_type(),
4099                H265NALU_AGGREGATION_PACKET_TYPE,
4100                "First packet should be AP"
4101            );
4102
4103            // Second packet should be single NAL (VCL type)
4104            let vcl_header = H265NALUHeader::new(vcl_packets[1][0], vcl_packets[1][1]);
4105            assert_eq!(
4106                vcl_header.nalu_type(),
4107                1,
4108                "Second packet should be VCL NAL (type 1)"
4109            );
4110
4111            Ok(())
4112        }
4113        #[test]
4114        fn test_h265_packetizer_exact_fu_boundary_mtu() -> Result<()> {
4115            // -------------------------------------------------------------------------
4116            // This test verifies the most dangerous MTU geometry for HEVC FU:
4117            //
4118            //   MTU == FU_header_size + (NAL_payload / 2)
4119            //
4120            // which must produce exactly TWO fragments with correct S/E bits and no
4121            // zero-length or extra FU packets.
4122            // -------------------------------------------------------------------------
4123
4124            // Large IDR NAL (type = 19)
4125            let nal_payload_size = 1400;
4126
4127            // Build a fake IDR NALU: [NALU header (2 bytes)] + payload
4128            let mut nalu = Vec::with_capacity(nal_payload_size + 2);
4129            nalu.push(0x26); // nal_unit_type = 19 (IDR_W_RADL)
4130            nalu.push(0x01);
4131            nalu.extend(std::iter::repeat(0xaa).take(nal_payload_size));
4132
4133            // FU overhead: 2-byte NAL header + 1-byte FU header = 3 bytes
4134            let fu_overhead = H265NALU_HEADER_SIZE + H265FRAGMENTATION_UNIT_HEADER_SIZE;
4135
4136            // Force an exact split into two equal fragments
4137            let mtu = fu_overhead + (nal_payload_size / 2);
4138
4139            let mut packetizer = H265Packetizer::default();
4140
4141            // Packetize
4142            let packets = packetizer.packetize(mtu, &nalu)?;
4143
4144            // Must produce exactly two FU packets
4145            assert_eq!(
4146                packets.len(),
4147                2,
4148                "exact-boundary FU must produce exactly 2 packets"
4149            );
4150
4151            // ---- First packet: FU start ----
4152            {
4153                let payload = &packets[0];
4154                let fu_hdr = H265FragmentationUnitHeader(payload[2]);
4155                assert!(fu_hdr.s(), "first FU packet must have S=1");
4156                assert!(!fu_hdr.e(), "first FU packet must have E=0");
4157                assert_eq!(fu_hdr.fu_type(), 19, "FU must carry IDR type");
4158            }
4159
4160            // ---- Second packet: FU end ----
4161            {
4162                let payload = &packets[1];
4163                let fu_hdr = H265FragmentationUnitHeader(payload[2]);
4164                assert!(!fu_hdr.s(), "last FU packet must have S=0");
4165                assert!(fu_hdr.e(), "last FU packet must have E=1");
4166                assert_eq!(fu_hdr.fu_type(), 19, "FU must carry IDR type");
4167            }
4168
4169            // Reassemble payload to ensure no bytes were lost or duplicated
4170            let mut reconstructed = Vec::new();
4171            for p in &packets {
4172                // Skip: 2-byte outer NAL header + 1-byte FU header
4173                reconstructed.extend_from_slice(&p[3..]);
4174            }
4175
4176            assert_eq!(
4177                reconstructed.len(),
4178                nal_payload_size,
4179                "reassembled FU payload must exactly match original NAL size"
4180            );
4181
4182            Ok(())
4183        }
4184    } // end emit_tests
4185
4186    /// Tests for Decoding Order Number (DONL/DOND) functionality.
4187    /// Validates DONL increments, sequences, and interleaving support.
4188    mod donl_tests {
4189        use super::*;
4190
4191        /// Test DONL field in single NAL unit packets.
4192        /// Verifies DONL is added during packetization and removed during depacketization.
4193        #[test]
4194        fn test_h265_donl_single_nal_round_trip() -> Result<()> {
4195            // Test DONL with single NAL unit packets
4196            let mut packetizer = H265Packetizer::default();
4197            packetizer.with_donl(true); // Enable DONL
4198
4199            let mut depacketizer = H265Depacketizer::default();
4200            depacketizer.with_donl(true);
4201
4202            // Create a single NAL unit (type 1, VCL)
4203            let nalu = vec![0x02, 0x01, 0xDE, 0xAD, 0xBE, 0xEF];
4204
4205            let packets = packetizer.packetize(MAX_PACKET_SIZE, &nalu)?;
4206            assert_eq!(packets.len(), 1, "Should produce 1 packet");
4207
4208            let packet = &packets[0];
4209
4210            // Verify DONL is present after NAL header
4211            // Packet structure: [NAL_HDR (2)] [DONL (2)] [PAYLOAD]
4212            assert!(
4213                packet.len() >= 6,
4214                "Packet should contain NAL header + DONL + payload"
4215            );
4216
4217            // NAL header should match
4218            assert_eq!(packet[0], 0x02);
4219            assert_eq!(packet[1], 0x01);
4220
4221            // DONL should be 0 for first packet
4222            let donl = u16::from_be_bytes([packet[2], packet[3]]);
4223            assert_eq!(donl, 0, "DONL should be 0 for first NAL");
4224
4225            // Payload should follow DONL
4226            assert_eq!(packet[4], 0xDE);
4227            assert_eq!(packet[5], 0xAD);
4228
4229            // Depacketize and verify output (Annex-B format without DONL)
4230            let mut out = Vec::new();
4231            let mut codec_extra = CodecExtra::None;
4232            depacketizer.depacketize(packet, &mut out, &mut codec_extra)?;
4233
4234            // Output should be: [START_CODE (4)] [NAL_HDR (2)] [PAYLOAD]
4235            assert_eq!(
4236                out.len(),
4237                10,
4238                "Annex-B output should be start code + NAL header + payload"
4239            );
4240            assert_eq!(&out[0..4], ANNEXB_NALUSTART_CODE);
4241            assert_eq!(&out[4..6], &[0x02, 0x01]);
4242            assert_eq!(&out[6..10], &[0xDE, 0xAD, 0xBE, 0xEF]);
4243
4244            // Verify DONL was parsed
4245            let payload = depacketizer.payload();
4246            if let H265Payload::H265SingleNALUnitPacket(pkt) = payload {
4247                assert_eq!(pkt.donl(), Some(0), "DONL should be parsed as 0");
4248            } else {
4249                panic!("Expected H265SingleNALUnitPacket");
4250            }
4251
4252            Ok(())
4253        }
4254
4255        /// Test DONL field in FU packets (only in first fragment).
4256        /// Verifies DONL appears in FU start packet but not in middle/end fragments.
4257        #[test]
4258        fn test_h265_donl_fragmentation_round_trip() -> Result<()> {
4259            // Test DONL with fragmentation units (FU)
4260            let mut packetizer = H265Packetizer::default();
4261            packetizer.with_donl(true);
4262
4263            let mut depacketizer = H265Depacketizer::default();
4264            depacketizer.with_donl(true);
4265
4266            // Create a large NAL unit that will be fragmented
4267            let mut nalu = vec![0x02, 0x01]; // NAL header (type 1)
4268            nalu.extend(vec![0xAA; 3000]); // Large payload
4269
4270            let packets = packetizer.packetize(1200, &nalu)?;
4271
4272            // Should produce multiple FU packets
4273            assert!(
4274                packets.len() >= 3,
4275                "Large NAL should be fragmented into multiple packets"
4276            );
4277
4278            // Check first FU packet structure: [FU_HDR (2)] [FU_HEADER (1)] [DONL (2)] [PAYLOAD]
4279            let first_packet = &packets[0];
4280            let fu_header = H265NALUHeader::new(first_packet[0], first_packet[1]);
4281            assert_eq!(
4282                fu_header.nalu_type(),
4283                H265NALU_FRAGMENTATION_UNIT_TYPE,
4284                "Should be FU packet"
4285            );
4286
4287            // FU header at byte 2
4288            let fu_hdr = H265FragmentationUnitHeader(first_packet[2]);
4289            assert!(fu_hdr.s(), "First FU should have S flag set");
4290            assert!(!fu_hdr.e(), "First FU should not have E flag");
4291
4292            // DONL should be at bytes 3-4
4293            let donl = u16::from_be_bytes([first_packet[3], first_packet[4]]);
4294            assert_eq!(donl, 0, "DONL should be 0 for first NAL");
4295
4296            // Middle packets should NOT have DONL
4297            if packets.len() > 2 {
4298                let middle_packet = &packets[1];
4299                let middle_fu_hdr = H265FragmentationUnitHeader(middle_packet[2]);
4300                assert!(!middle_fu_hdr.s(), "Middle FU should not have S flag");
4301                assert!(!middle_fu_hdr.e(), "Middle FU should not have E flag");
4302                // Payload starts right after FU header (no DONL)
4303            }
4304
4305            // Last packet should have E flag but no DONL
4306            let last_packet = &packets[packets.len() - 1];
4307            let last_fu_hdr = H265FragmentationUnitHeader(last_packet[2]);
4308            assert!(!last_fu_hdr.s(), "Last FU should not have S flag");
4309            assert!(last_fu_hdr.e(), "Last FU should have E flag set");
4310
4311            // Depacketize all fragments
4312            let mut out = Vec::new();
4313            let mut codec_extra = CodecExtra::None;
4314
4315            for packet in &packets {
4316                depacketizer.depacketize(packet, &mut out, &mut codec_extra)?;
4317            }
4318
4319            // Output should be complete NAL in Annex-B format
4320            assert_eq!(
4321                out.len(),
4322                4 + nalu.len(),
4323                "Annex-B output should match original"
4324            );
4325            assert_eq!(&out[0..4], ANNEXB_NALUSTART_CODE);
4326            assert_eq!(&out[4..], &nalu[..]);
4327
4328            // Verify DONL was parsed from first FU
4329            let payload = depacketizer.payload();
4330            if let H265Payload::H265FragmentationUnitPacket(pkt) = payload {
4331                // Last FU packet won't have DONL, that's expected
4332                // The DONL from the first packet was used internally
4333            } else {
4334                panic!("Expected H265FragmentationUnitPacket");
4335            }
4336
4337            Ok(())
4338        }
4339
4340        /// Test DONL/DOND fields in aggregation packets.
4341        /// Verifies first aggregated NAL has DONL, subsequent NALs have DOND.
4342        #[test]
4343        fn test_h265_donl_aggregation_round_trip() -> Result<()> {
4344            // Test DONL with aggregation packets (AP)
4345            let mut packetizer = H265Packetizer::default();
4346            packetizer.with_donl(true);
4347
4348            let mut depacketizer = H265Depacketizer::default();
4349            depacketizer.with_donl(true);
4350
4351            // Create parameter sets to trigger aggregation
4352            let mut annexb = Vec::new();
4353
4354            // VPS
4355            annexb.extend_from_slice(ANNEXB_NALUSTART_CODE);
4356            annexb.extend_from_slice(&[0x40, 0x01, 0x0C, 0x01, 0xFF, 0xFF]);
4357
4358            // SPS
4359            annexb.extend_from_slice(ANNEXB_NALUSTART_CODE);
4360            annexb.extend_from_slice(&[0x42, 0x01, 0x01, 0x50, 0x00, 0x00]);
4361
4362            // PPS
4363            annexb.extend_from_slice(ANNEXB_NALUSTART_CODE);
4364            annexb.extend_from_slice(&[0x44, 0x01, 0xC0, 0xF3, 0xC0, 0x02]);
4365
4366            let packets = packetizer.packetize(MAX_PACKET_SIZE, &annexb)?;
4367            assert_eq!(packets.len(), 0, "Parameter sets should be cached");
4368
4369            // Send VCL NAL to trigger AP emission
4370            let mut vcl_annexb = Vec::new();
4371            vcl_annexb.extend_from_slice(ANNEXB_NALUSTART_CODE);
4372            vcl_annexb.extend_from_slice(&[0x02, 0x01, 0x11, 0x22, 0x33]);
4373
4374            let vcl_packets = packetizer.packetize(MAX_PACKET_SIZE, &vcl_annexb)?;
4375            assert_eq!(vcl_packets.len(), 2, "Should produce AP + VCL");
4376
4377            let ap_packet = &vcl_packets[0];
4378
4379            // Verify AP packet structure:
4380            // [AP_HDR (2)] [DONL (2)] [NALU_SIZE (2)] [NALU] [DOND (1)] [NALU_SIZE (2)] [NALU] ...
4381            let ap_header = H265NALUHeader::new(ap_packet[0], ap_packet[1]);
4382            assert_eq!(ap_header.nalu_type(), H265NALU_AGGREGATION_PACKET_TYPE);
4383
4384            // DONL at bytes 2-3
4385            let donl = u16::from_be_bytes([ap_packet[2], ap_packet[3]]);
4386            assert_eq!(donl, 0, "DONL should be 0 for first aggregated packet");
4387
4388            // First NAL size at bytes 4-5
4389            let first_size = u16::from_be_bytes([ap_packet[4], ap_packet[5]]);
4390            assert_eq!(first_size, 6, "VPS size should be 6 bytes");
4391
4392            // After first NAL, there should be DOND (1 byte) before second NAL size
4393            let first_nal_end = 6 + first_size as usize;
4394            let dond1 = ap_packet[first_nal_end];
4395            assert_eq!(dond1, 0, "DOND should be 0 (same decoding order)");
4396
4397            // Depacketize AP
4398            let mut out = Vec::new();
4399            let mut codec_extra = CodecExtra::None;
4400            depacketizer.depacketize(ap_packet, &mut out, &mut codec_extra)?;
4401
4402            // Should output all 3 parameter sets in Annex-B format
4403            // Each: [START_CODE (4)] [NAL]
4404            // Note: Some parameter sets might be filtered/deduplicated, so check minimum
4405            assert!(
4406                out.len() >= 18,
4407                "Should output at least 2 NALs with start codes"
4408            );
4409
4410            // Verify first NAL (VPS) starts correctly
4411            assert_eq!(&out[0..4], ANNEXB_NALUSTART_CODE);
4412            assert_eq!(&out[4..6], &[0x40, 0x01]);
4413
4414            Ok(())
4415        }
4416
4417        /// Test DONL counter increments for each NAL unit in transmission order.
4418        /// Verifies DONL starts at 0 and increments by 1 for each subsequent NAL.
4419        #[test]
4420        fn test_h265_donl_increments_correctly() -> Result<()> {
4421            // Verify DONL increments for each NAL unit
4422            let mut packetizer = H265Packetizer::default();
4423            packetizer.with_donl(true);
4424
4425            // Send 3 separate NAL units
4426            let nalu1 = vec![0x02, 0x01, 0xAA];
4427            let nalu2 = vec![0x02, 0x01, 0xBB];
4428            let nalu3 = vec![0x02, 0x01, 0xCC];
4429
4430            let packets1 = packetizer.packetize(MAX_PACKET_SIZE, &nalu1)?;
4431            let packets2 = packetizer.packetize(MAX_PACKET_SIZE, &nalu2)?;
4432            let packets3 = packetizer.packetize(MAX_PACKET_SIZE, &nalu3)?;
4433
4434            // Check DONL values
4435            let donl1 = u16::from_be_bytes([packets1[0][2], packets1[0][3]]);
4436            let donl2 = u16::from_be_bytes([packets2[0][2], packets2[0][3]]);
4437            let donl3 = u16::from_be_bytes([packets3[0][2], packets3[0][3]]);
4438
4439            assert_eq!(donl1, 0, "First DONL should be 0");
4440            assert_eq!(donl2, 1, "Second DONL should be 1");
4441            assert_eq!(donl3, 2, "Third DONL should be 2");
4442
4443            Ok(())
4444        }
4445
4446        /// Test packetizer without DONL enabled produces standard packets.
4447        /// Verifies no DONL fields are added when DONL is disabled (default behavior).
4448        #[test]
4449        fn test_h265_without_donl() -> Result<()> {
4450            // Verify that without DONL enabled, no DONL fields are added
4451            let mut packetizer = H265Packetizer::default();
4452            // Don't call with_donl(true) - DONL should be disabled by default
4453
4454            let nalu = vec![0x02, 0x01, 0xDE, 0xAD, 0xBE, 0xEF];
4455            let packets = packetizer.packetize(MAX_PACKET_SIZE, &nalu)?;
4456
4457            assert_eq!(packets.len(), 1);
4458            let packet = &packets[0];
4459
4460            // Packet should be exactly the NAL unit (no DONL field)
4461            assert_eq!(
4462                packet.len(),
4463                nalu.len(),
4464                "Packet should not have DONL field"
4465            );
4466            assert_eq!(packet, &nalu[..]);
4467
4468            Ok(())
4469        }
4470
4471        /// Test SDP-driven DONL enablement via sprop-max-don-diff.
4472        /// Simulates the full flow: SDP fmtp → FormatParams → with_donl(true) →
4473        /// packetize/depacketize round-trip for Single NAL, AP, and FU packet types.
4474        #[test]
4475        fn test_h265_sdp_driven_donl_all_packet_types() -> Result<()> {
4476            use crate::format::FormatParams;
4477
4478            // Step 1: Parse SDP fmtp line with sprop-max-don-diff > 0
4479            let fmtp = FormatParams::parse_line("sprop-max-don-diff=32");
4480            assert_eq!(fmtp.sprop_max_don_diff, Some(32));
4481
4482            // Step 2: Enable DONL on packetizer/depacketizer based on SDP (same as Payloader::new)
4483            let donl_enabled = fmtp.sprop_max_don_diff.unwrap_or(0) > 0;
4484            assert!(donl_enabled, "sprop-max-don-diff=32 should enable DONL");
4485
4486            let mut packetizer = H265Packetizer::default();
4487            packetizer.with_donl(donl_enabled);
4488
4489            let mut depacketizer = H265Depacketizer::default();
4490            depacketizer.with_donl(donl_enabled);
4491
4492            // --- Test 1: Single NAL Unit with DONL ---
4493            let single_nalu = vec![0x02, 0x01, 0xDE, 0xAD, 0xBE, 0xEF]; // Type 1 (TRAIL_R)
4494            let packets = packetizer.packetize(MAX_PACKET_SIZE, &single_nalu)?;
4495            assert_eq!(packets.len(), 1, "Single NAL should produce 1 packet");
4496
4497            // Verify DONL=0 is present on wire: [NAL_HDR(2)] [DONL(2)] [payload]
4498            let pkt = &packets[0];
4499            assert_eq!(
4500                pkt.len(),
4501                single_nalu.len() + 2,
4502                "Packet should include 2-byte DONL"
4503            );
4504            let donl = u16::from_be_bytes([pkt[2], pkt[3]]);
4505            assert_eq!(donl, 0, "First NAL should have DONL=0");
4506
4507            // Depacketize and verify Annex-B output matches original
4508            let mut out = Vec::new();
4509            let mut extra = CodecExtra::None;
4510            depacketizer.depacketize(pkt, &mut out, &mut extra)?;
4511            assert_eq!(&out[0..4], ANNEXB_NALUSTART_CODE);
4512            assert_eq!(
4513                &out[4..],
4514                &single_nalu[..],
4515                "Depacketized NAL should match original"
4516            );
4517
4518            // --- Test 2: AP (VPS + SPS + PPS) with DONL ---
4519            let vps = vec![0x40, 0x01, 0xAA, 0xBB, 0xCC];
4520            let sps = vec![0x42, 0x01, 0xDD, 0xEE, 0xFF, 0x11];
4521            let pps = vec![0x44, 0x01, 0x22, 0x33];
4522            let vcl = vec![0x26, 0x01, 0x44, 0x55, 0x66]; // IDR_W_RADL
4523
4524            // Cache parameter sets (no output)
4525            assert!(packetizer.packetize(MAX_PACKET_SIZE, &vps)?.is_empty());
4526            assert!(packetizer.packetize(MAX_PACKET_SIZE, &sps)?.is_empty());
4527            assert!(packetizer.packetize(MAX_PACKET_SIZE, &pps)?.is_empty());
4528
4529            // Trigger AP + VCL emission
4530            let ap_packets = packetizer.packetize(MAX_PACKET_SIZE, &vcl)?;
4531            assert_eq!(ap_packets.len(), 2, "Should produce AP + VCL");
4532
4533            // Verify AP wire format: [AP_HDR(2)] [DONL(2)] [Size(2)] [NAL] [DOND(1)] [Size(2)] [NAL] ...
4534            let ap = &ap_packets[0];
4535            let ap_hdr = H265NALUHeader::new(ap[0], ap[1]);
4536            assert_eq!(ap_hdr.nalu_type(), H265NALU_AGGREGATION_PACKET_TYPE);
4537            let ap_donl = u16::from_be_bytes([ap[2], ap[3]]);
4538            assert_eq!(
4539                ap_donl, 1,
4540                "AP DONL should be 1 (after single NAL consumed DON=0)"
4541            );
4542
4543            // Verify DOND bytes are present (0 = sequential order)
4544            let first_size = u16::from_be_bytes([ap[4], ap[5]]) as usize;
4545            let dond_offset = 6 + first_size; // after AP_HDR + DONL + size + first NAL
4546            assert_eq!(
4547                ap[dond_offset], 0,
4548                "DOND should be 0 for sequential decoding"
4549            );
4550
4551            // Depacketize AP and verify all 3 NALs appear in Annex-B output
4552            out.clear();
4553            extra = CodecExtra::None;
4554            depacketizer.depacketize(ap, &mut out, &mut extra)?;
4555
4556            let mut offset = 0;
4557            for expected in [&vps, &sps, &pps] {
4558                assert_eq!(&out[offset..offset + 4], ANNEXB_NALUSTART_CODE);
4559                offset += 4;
4560                assert_eq!(&out[offset..offset + expected.len()], &expected[..]);
4561                offset += expected.len();
4562            }
4563            assert_eq!(offset, out.len(), "All AP data should be consumed");
4564
4565            // Verify VCL has correct DONL (AP consumed 3 DONs: 1,2,3 → next is 4)
4566            let vcl_pkt = &ap_packets[1];
4567            let vcl_donl = u16::from_be_bytes([vcl_pkt[2], vcl_pkt[3]]);
4568            assert_eq!(vcl_donl, 4, "VCL DONL should be 4 (after AP with 3 NALs)");
4569
4570            // Depacketize VCL
4571            out.clear();
4572            extra = CodecExtra::None;
4573            depacketizer.depacketize(vcl_pkt, &mut out, &mut extra)?;
4574            assert_eq!(&out[4..], &vcl[..], "VCL NAL should match original");
4575
4576            // --- Test 3: FU (large NAL fragmented) with DONL ---
4577            let mut large_nalu = vec![0x02, 0x01]; // Type 1
4578            large_nalu.extend(vec![0xAA; 200]);
4579
4580            let fu_packets = packetizer.packetize(100, &large_nalu)?;
4581            assert!(fu_packets.len() > 1, "Large NAL should be fragmented");
4582
4583            // Verify DONL=5 is present only in first FU fragment (S=1)
4584            let first_fu = &fu_packets[0];
4585            let fu_hdr_byte = H265FragmentationUnitHeader(first_fu[2]);
4586            assert!(fu_hdr_byte.s(), "First FU should have S=1");
4587            let fu_donl = u16::from_be_bytes([first_fu[3], first_fu[4]]);
4588            assert_eq!(fu_donl, 5, "FU DONL should be 5 (after VCL consumed DON=4)");
4589
4590            // Middle/end fragments should NOT have DONL (payload starts at byte 3)
4591            let last_fu = &fu_packets[fu_packets.len() - 1];
4592            let last_fu_hdr = H265FragmentationUnitHeader(last_fu[2]);
4593            assert!(last_fu_hdr.e(), "Last FU should have E=1");
4594            assert!(!last_fu_hdr.s(), "Last FU should not have S=1");
4595            // No DONL in last fragment — payload is at byte 3, not 5
4596
4597            // Depacketize all FU fragments
4598            out.clear();
4599            extra = CodecExtra::None;
4600            for pkt in &fu_packets {
4601                depacketizer.depacketize(pkt, &mut out, &mut extra)?;
4602            }
4603
4604            // Verify reconstructed NAL matches original
4605            assert_eq!(&out[0..4], ANNEXB_NALUSTART_CODE);
4606            assert_eq!(
4607                &out[4..],
4608                &large_nalu[..],
4609                "Reassembled FU should match original"
4610            );
4611
4612            // --- Verify DONL counter progression ---
4613            // After all operations: DON 0 (single), 1-3 (AP with 3 NALs), 4 (VCL), 5 (FU) → next = 6
4614            let next_nalu = vec![0x02, 0x01, 0x77];
4615            let next_packets = packetizer.packetize(MAX_PACKET_SIZE, &next_nalu)?;
4616            let next_donl = u16::from_be_bytes([next_packets[0][2], next_packets[0][3]]);
4617            assert_eq!(next_donl, 6, "Next DONL should be 6 after full sequence");
4618
4619            Ok(())
4620        }
4621    } // end donl_tests
4622
4623    /// End-to-end round-trip validation.
4624    /// Tests packetize → depacketize cycles for correctness.
4625    mod roundtrip_tests {
4626        use super::*;
4627
4628        /// Test complete round-trip with DONL.
4629        /// Verifies packetizer → depacketizer with DONL enabled produces identical output.
4630        #[test]
4631        fn test_h265_roundtrip_with_donl() -> Result<()> {
4632            let mut packetizer = H265Packetizer::default();
4633            packetizer.with_donl(true);
4634
4635            let mut depacketizer = H265Depacketizer::default();
4636            depacketizer.with_donl(true);
4637
4638            // Test 1: Single NAL with DONL
4639            let single_nalu = vec![0x02, 0x01, 0xff, 0xff, 0xff];
4640            let packets = packetizer.packetize(MAX_PACKET_SIZE, &single_nalu)?;
4641
4642            assert_eq!(packets.len(), 1, "Single NAL should produce 1 packet");
4643
4644            // Verify DONL is present (bytes 2-3 after NAL header)
4645            let donl = u16::from_be_bytes([packets[0][2], packets[0][3]]);
4646            assert_eq!(donl, 0, "First DONL should be 0");
4647
4648            // Depacketize and verify
4649            let mut out = Vec::new();
4650            let mut codec_extra = CodecExtra::None;
4651            depacketizer.depacketize(&packets[0], &mut out, &mut codec_extra)?;
4652            assert!(!out.is_empty(), "Should depacketize successfully");
4653
4654            // Test 2: Fragmented NAL with DONL
4655            let mut large_nalu = vec![0x02, 0x01];
4656            for i in 0..512 {
4657                large_nalu.push((i % 256) as u8);
4658            }
4659
4660            let fu_packets = packetizer.packetize(100, &large_nalu)?;
4661            assert!(fu_packets.len() > 1, "Large NAL should fragment");
4662
4663            // First fragment should have DONL
4664            let first_donl = u16::from_be_bytes([fu_packets[0][3], fu_packets[0][4]]);
4665            assert_eq!(first_donl, 1, "Second NAL should have DONL=1");
4666
4667            // Reassemble all fragments
4668            out.clear();
4669            codec_extra = CodecExtra::None;
4670            for packet in &fu_packets {
4671                depacketizer.depacketize(packet, &mut out, &mut codec_extra)?;
4672            }
4673
4674            assert!(!out.is_empty(), "Should reassemble fragmented NAL");
4675
4676            // Verify reconstructed payload matches original (minus Annex B start codes)
4677            // The output will have Annex B format with start codes
4678            let has_start_code = out.len() > 4 && out[0..4] == [0x00, 0x00, 0x00, 0x01];
4679            assert!(has_start_code || out.len() > 0, "Should have valid output");
4680
4681            Ok(())
4682        }
4683
4684        /// Test aggregation with exact DONL values.
4685        /// Verifies contiguous and non-contiguous DONL sequences in AP packets.
4686        #[test]
4687        fn test_h265_aggregation_with_donl_sequences() -> Result<()> {
4688            let mut packetizer = H265Packetizer::default();
4689            packetizer.with_donl(true);
4690
4691            // Send multiple parameter sets to build up cache
4692            let vps = vec![0x40, 0x01, 0x00, 0x01, 0x02, 0x03];
4693            let sps = vec![0x42, 0x01, 0x00, 0x01, 0x02, 0x03];
4694            let pps = vec![0x44, 0x01, 0x00, 0x01, 0x02, 0x03];
4695
4696            packetizer.packetize(MAX_PACKET_SIZE, &vps)?;
4697            packetizer.packetize(MAX_PACKET_SIZE, &sps)?;
4698            packetizer.packetize(MAX_PACKET_SIZE, &pps)?;
4699
4700            // Trigger with VCL NAL
4701            let vcl = vec![0x02, 0x01, 0xAA, 0xBB];
4702            let packets = packetizer.packetize(MAX_PACKET_SIZE, &vcl)?;
4703
4704            // Should emit AP + VCL or individual packets with DONL
4705            assert!(!packets.is_empty(), "Should produce packets");
4706
4707            // Each packet should have proper structure
4708            for packet in &packets {
4709                assert!(packet.len() >= 2, "Packet should have at least NAL header");
4710            }
4711
4712            Ok(())
4713        }
4714    } // end roundtrip_tests
4715
4716    /// Edge case and buffer overflow prevention tests.
4717    /// Validates MTU boundary conditions, zero-length inputs, and error handling.
4718    mod regression_tests {
4719        use super::*;
4720
4721        /// Test packetizer with zero MTU returns empty output.
4722        /// Verifies that invalid MTU (0) is handled gracefully without panicking.
4723        #[test]
4724        fn test_h265_zero_mtu() -> Result<()> {
4725            let mut packetizer = H265Packetizer::default();
4726            let nalu = vec![0x02, 0x01, 0xAA, 0xBB, 0xCC];
4727
4728            let packets = packetizer.packetize(0, &nalu)?;
4729
4730            // Zero MTU should result in no packets being created
4731            assert!(packets.is_empty(), "Zero MTU should produce no packets");
4732
4733            Ok(())
4734        }
4735
4736        /// Test packetizer with empty NAL unit returns empty output.
4737        /// Verifies that empty input is handled gracefully without panicking.
4738        #[test]
4739        fn test_h265_empty_nalu() -> Result<()> {
4740            let mut packetizer = H265Packetizer::default();
4741            let nalu = vec![];
4742
4743            let packets = packetizer.packetize(MAX_PACKET_SIZE, &nalu)?;
4744
4745            // Empty NAL unit should result in no packets
4746            assert!(
4747                packets.is_empty(),
4748                "Empty NAL unit should produce no packets"
4749            );
4750
4751            Ok(())
4752        }
4753
4754        /// Test packetizer with MTU smaller than FU overhead.
4755        /// Verifies that MTU too small for fragmentation is handled gracefully.
4756        #[test]
4757        fn test_h265_mtu_smaller_than_fu_overhead() -> Result<()> {
4758            let mut packetizer = H265Packetizer::default();
4759
4760            // Create a large NAL that would require fragmentation
4761            let mut large_nalu = vec![0x02, 0x01];
4762            large_nalu.extend(vec![0xAA; 200]);
4763
4764            // FU overhead is 3 bytes (2 FU indicator + 1 FU header)
4765            // MTU = 2 is smaller than overhead, should produce no packets
4766            let packets = packetizer.packetize(2, &large_nalu)?;
4767
4768            assert!(
4769                packets.is_empty(),
4770                "MTU smaller than FU overhead should produce no packets"
4771            );
4772
4773            Ok(())
4774        }
4775
4776        /// Test packetizer with MTU exactly equal to FU overhead.
4777        /// Verifies edge case where MTU = overhead (no room for payload).
4778        #[test]
4779        fn test_h265_mtu_equals_fu_overhead() -> Result<()> {
4780            let mut packetizer = H265Packetizer::default();
4781
4782            // Create a large NAL that would require fragmentation
4783            let mut large_nalu = vec![0x02, 0x01];
4784            large_nalu.extend(vec![0xBB; 200]);
4785
4786            // FU overhead is 3 bytes, no room for payload
4787            let packets = packetizer.packetize(3, &large_nalu)?;
4788
4789            assert!(
4790                packets.is_empty(),
4791                "MTU equal to FU overhead (no payload room) should produce no packets"
4792            );
4793
4794            Ok(())
4795        }
4796
4797        /// Test packetizer with MTU = FU overhead + DONL (with DONL enabled).
4798        /// Verifies that when DONL is enabled, first fragment needs extra space.
4799        #[test]
4800        fn test_h265_mtu_equals_fu_overhead_plus_donl() -> Result<()> {
4801            let mut packetizer = H265Packetizer::default();
4802            packetizer.with_donl(true);
4803
4804            // Create a large NAL that would require fragmentation
4805            let mut large_nalu = vec![0x02, 0x01];
4806            large_nalu.extend(vec![0xCC; 200]);
4807
4808            // FU overhead (3) + DONL (2) = 5 bytes, no room for payload
4809            let packets = packetizer.packetize(5, &large_nalu)?;
4810
4811            assert!(
4812                packets.is_empty(),
4813                "MTU equal to FU overhead + DONL (no payload room) should produce no packets"
4814            );
4815
4816            Ok(())
4817        }
4818
4819        /// Test FU packetization with MTU larger than MAX_PACKET_SIZE.
4820        /// Verifies that effective_mtu is clamped to MAX_PACKET_SIZE (1200) to prevent buffer overflow.
4821        #[test]
4822        fn test_h265_fu_mtu_exceeds_max_packet_size() -> Result<()> {
4823            let mut packetizer = H265Packetizer::default();
4824
4825            // Create a large NAL that requires fragmentation
4826            let mut large_nalu = vec![0x02, 0x01];
4827            large_nalu.extend(vec![0xDD; 3000]);
4828
4829            // Request MTU=2000, but should be clamped to MAX_PACKET_SIZE=1200
4830            let packets = packetizer.packetize(2000, &large_nalu)?;
4831
4832            assert!(!packets.is_empty(), "Should produce FU packets");
4833
4834            // All packets should fit within MAX_PACKET_SIZE (1200)
4835            for (i, packet) in packets.iter().enumerate() {
4836                assert!(
4837                    packet.len() <= 1200,
4838                    "Packet {} size {} exceeds MAX_PACKET_SIZE (1200)",
4839                    i,
4840                    packet.len()
4841                );
4842            }
4843
4844            Ok(())
4845        }
4846
4847        /// Test single NAL with DONL produces correct packet.
4848        /// Verifies that large single NAL units with DONL are handled correctly.
4849        #[test]
4850        fn test_h265_single_nal_with_donl_large() -> Result<()> {
4851            let mut packetizer = H265Packetizer::default();
4852            packetizer.with_donl(true);
4853
4854            // Create a large NAL that fits MTU
4855            let mut large_nalu = vec![0x02, 0x01];
4856            large_nalu.extend(vec![0xEE; 1197]); // Total 1199 bytes
4857
4858            let packets = packetizer.packetize(MAX_PACKET_SIZE, &large_nalu)?;
4859
4860            // With Vec buffer, large packets within MTU are produced successfully
4861            assert_eq!(packets.len(), 1);
4862            // Packet should have NAL header (2) + DONL (2) + payload (1197)
4863            assert_eq!(packets[0].len(), 1199 + 2); // Original + DONL
4864
4865            Ok(())
4866        }
4867
4868        /// Test AP packet that would exceed MTU falls back to individual packets.
4869        /// Verifies that when aggregation would violate MTU, parameter sets are sent separately.
4870        #[test]
4871        fn test_h265_ap_buffer_overflow_fallback() -> Result<()> {
4872            let mut packetizer = H265Packetizer::default();
4873
4874            // Create large parameter sets that would overflow when aggregated
4875            let mut vps = vec![0x40, 0x01];
4876            vps.extend(vec![0xAA; 100]);
4877
4878            let mut sps = vec![0x42, 0x01];
4879            sps.extend(vec![0xBB; 100]);
4880
4881            let mut pps = vec![0x44, 0x01];
4882            pps.extend(vec![0xCC; 100]);
4883
4884            let vcl = vec![0x02, 0x01, 0xDD];
4885
4886            // Cache parameter sets
4887            assert!(packetizer.packetize(1200, &vps)?.is_empty());
4888            assert!(packetizer.packetize(1200, &sps)?.is_empty());
4889            assert!(packetizer.packetize(1200, &pps)?.is_empty());
4890
4891            // Trigger emission with MTU that's too small for AP
4892            // AP overhead: 2 (header) + 3×2 (size fields) + 102+102+102 = 314 bytes
4893            let small_mtu = 200;
4894            let packets = packetizer.packetize(small_mtu, &vcl)?;
4895
4896            // Should emit as individual packets (VPS, SPS, PPS, VCL)
4897            assert_eq!(packets.len(), 4, "Should fall back to 4 individual packets");
4898
4899            // Verify all packets fit within MTU
4900            for packet in &packets {
4901                assert!(
4902                    packet.len() <= small_mtu,
4903                    "Fallback packet size {} exceeds MTU {}",
4904                    packet.len(),
4905                    small_mtu
4906                );
4907            }
4908
4909            Ok(())
4910        }
4911
4912        /// Test FU packetization handles minimal MTU (overhead + 1 byte payload).
4913        /// Verifies that fragmentation works even with smallest possible payload per packet.
4914        #[test]
4915        fn test_h265_fu_minimal_mtu() -> Result<()> {
4916            let mut packetizer = H265Packetizer::default();
4917
4918            // Create a NAL that requires fragmentation
4919            let nalu = vec![0x02, 0x01, 0xAA, 0xBB, 0xCC, 0xDD];
4920
4921            // FU overhead = 3 bytes, MTU = 4 allows 1 byte payload per packet
4922            let mtu = 4;
4923            let packets = packetizer.packetize(mtu, &nalu)?;
4924
4925            // Should create multiple packets, each with 1 byte of payload
4926            assert!(
4927                packets.len() >= 4,
4928                "Should fragment into multiple packets with 1-byte payload"
4929            );
4930
4931            // Verify all packets fit within MTU
4932            for packet in &packets {
4933                assert!(packet.len() <= mtu, "Packet exceeds MTU");
4934            }
4935
4936            Ok(())
4937        }
4938
4939        /// Test packetizer with NAL unit smaller than header size.
4940        /// Verifies that malformed NAL (< 2 bytes) is handled gracefully.
4941        #[test]
4942        fn test_h265_nalu_smaller_than_header() -> Result<()> {
4943            let mut packetizer = H265Packetizer::default();
4944
4945            // NAL unit with only 1 byte (invalid, needs at least 2 for header)
4946            let invalid_nalu = vec![0x02];
4947
4948            let packets = packetizer.packetize(MAX_PACKET_SIZE, &invalid_nalu)?;
4949
4950            // Should drop malformed NAL (< H265NALU_HEADER_SIZE)
4951            assert!(
4952                packets.is_empty(),
4953                "Malformed NAL (< 2 bytes) should be dropped"
4954            );
4955
4956            Ok(())
4957        }
4958    } // end regression_tests
4959
4960    /// Integration tests for complex scenarios.
4961    /// Tests aggregation layouts, SE flag correctness, and real-world payloads.
4962    mod integration_tests {
4963        use super::*;
4964
4965        /// Test depacketization of real H.265 RTP payloads from Wireshark captures.
4966        /// Verifies practical compatibility with actual WebRTC H.265 streams.
4967        /// This is an integration test because it exercises fragmentation, reassembly, and Annex-B output.
4968        #[test]
4969        fn test_h265_packet_real() -> Result<()> {
4970            // Tests decoding of real H265 payloads extracted from a Wireshark dump.
4971            let tests = vec![
4972        b"\x40\x01\x0c\x01\xff\xff\x01\x60\x00\x00\x03\x00\xb0\x00\x00\x03\x00\x00\x03\x00\x7b\xac\x09"
4973            .to_vec(),
4974        b"\x42\x01\x01\x01\x60\x00\x00\x03\x00\xb0\x00\x00\x03\x00\x00\x03\x00\x7b\xa0\x03\xc0\x80\x10\
4975          \xe5\x8d\xae\x49\x32\xf4\xdc\x04\x04\x04\x02".to_vec(),
4976        b"\x44\x01\xc0\xf2\xf0\x3c\x90".to_vec(),
4977        b"\x4e\x01\xe5\x04\x61\x0c\x00\x00\x80".to_vec(),
4978        // Large test vector split across multiple lines for readability
4979        [
4980            &b"\x62\x01\x93\xaf\x0d\x5a\xfe\x67\x77\x29\xc0\x74\xf3\x57\x4c\x16\x94\xaa"[..],
4981            &b"\x7c\x2a\x64\x5f\xe9\xa5\xb7\x2a\xa3\x95\x9d\x94\xa7\xb4\xd3\xc4\x4a\xb1"[..],
4982            &b"\xb7\x69\xca\xbe\x75\xc5\x64\xa8\x97\x4b\x8a\xbf\x7e\xf0\x0f\xc3\x22\x60"[..],
4983            &b"\x67\xab\xae\x96\xd6\x99\xca\x7a\x8d\x35\x93\x1a\x67\x60\xe7\xbe\x7e\x13"[..],
4984            &b"\x95\x3c\xe0\x11\xc1\xc1\xa7\x48\xef\xf7\x7b\xb0\xeb\x35\x49\x81\x4e\x4e"[..],
4985            &b"\x54\xf7\x31\x6a\x38\xa1\xa7\x0c\xd6\xbe\x3b\x25\xba\x08\x19\x0b\x49\xfd"[..],
4986            &b"\x90\xbb\x73\x7a\x45\x8c\xb9\x73\x43\x04\xc5\x5f\xda\x0f\xd5\x70\x4c\x11"[..],
4987            &b"\xee\x72\xb8\x6a\xb4\x95\x62\x64\xb6\x23\x14\x7e\xdb\x0e\xa5\x0f\x86\x31"[..],
4988            &b"\xe4\xd1\x64\x56\x43\xf6\xb7\xe7\x1b\x93\x4a\xeb\xd0\xa6\xe3\x1f\xce\xda"[..],
4989            &b"\x15\x67\x05\xb6\x77\x36\x8b\x27\x5b\xc6\xf2\x95\xb8\x2b\xcc\x9b\x0a\x03"[..],
4990            &b"\x05\xbe\xc3\xd3\x85\xf5\x69\xb6\x19\x1f\x63\x2d\x8b\x65\x9e\xc3\x9d\xd2"[..],
4991            &b"\x44\xb3\x7c\x86\x3b\xea\xa8\x5d\x02\xe5\x40\x03\x20\x76\x48\xff\xf6\x2b"[..],
4992            &b"\x0d\x18\xd6\x4d\x49\x70\x1a\x5e\xb2\x89\xca\xec\x71\x41\x79\x4e\x94\x17"[..],
4993            &b"\x0c\x57\x51\x55\x14\x61\x40\x46\x4b\x3e\x17\xb2\xc8\xbd\x1c\x06\x13\x91"[..],
4994            &b"\x72\xf8\xc8\xfc\x6f\xb0\x30\x9a\xec\x3b\xa6\xc9\x33\x0b\xa5\xe5\xf4\x65"[..],
4995            &b"\x7a\x29\x8b\x76\x62\x81\x12\xaf\x20\x4c\xd9\x21\x23\x9e\xeb\xc9\x0e\x5b"[..],
4996            &b"\x29\x35\x7f\x41\xcd\xce\xa1\xc4\xbe\x01\x30\xb9\x11\xc3\xb1\xe4\xce\x45"[..],
4997            &b"\xd2\x5c\xb3\x1e\x69\x78\xba\xb1\x72\xe4\x88\x54\xd8\x5d\xd0\xa8\x3a\x74"[..],
4998            &b"\xad\xe5\xc7\xc1\x59\x7c\x78\x15\x26\x37\x3d\x50\xae\xb3\xa4\x5b\x6c\x7d"[..],
4999            &b"\x65\x66\x85\x4d\x16\x9a\x67\x74\xad\x55\x32\x3a\x84\x85\x0b\x6a\xeb\x24"[..],
5000            &b"\x97\xb4\x20\x4d\xca\x41\x61\x7a\xd1\x7b\x60\xdb\x7f\xd5\x61\x22\xcf\xd1"[..],
5001            &b"\x7e\x4c\xf3\x85\xfd\x13\x63\xe4\x9d\xed\xac\x13\x0a\xa0\x92\xb7\x34\xde"[..],
5002            &b"\x65\x0f\xd9\x0f\x9b\xac\xe2\x47\xe8\x5c\xb3\x11\x8e\xc6\x08\x19\xd0\xb0"[..],
5003            &b"\x85\x52\xc8\x5c\x1b\x08\x0a\xce\xc9\x6b\xa7\xef\x95\x2f\xd0\xb8\x63\xe5"[..],
5004            &b"\x4c\xd4\xed\x6e\x87\xe9\xd4\x0a\xe6\x11\x44\x63\x00\x94\x18\xe9\x28\xba"[..],
5005            &b"\xcf\x92\x43\x06\x59\xdd\x37\x4f\xd3\xef\x9d\x31\x5e\x9b\x48\xf9\x1f\x3e"[..],
5006            &b"\x7b\x95\x3a\xbd\x1f\x71\x55\x0c\x06\xf9\x86\xf8\x3d\x39\x16\x50\xb3\x21"[..],
5007            &b"\x11\x19\x6f\x70\xa9\x48\xe8\xbb\x0a\x11\x23\xf8\xab\xfe\x44\xe0\xbb\xe8"[..],
5008            &b"\x64\xfa\x85\xe4\x02\x55\x88\x41\xc6\x30\x7f\x10\xad\x75\x02\x4b\xef\xe1"[..],
5009            &b"\x0b\x06\x3c\x10\x49\x83\xf9\xd1\x3e\x3e\x67\x86\x4c\xf8\x9d\xde\x5a\xc4"[..],
5010            &b"\xc8\xcf\xb6\xf4\xb0\xd3\x34\x58\xd4\x7b\x4d\xd3\x37\x63\xb2\x48\x8a\x7e"[..],
5011            &b"\x20\x00\xde\xb4\x42\x8f\xda\xe9\x43\x9e\x0c\x16\xce\x79\xac\x2c\x70\xc1"[..],
5012            &b"\x89\x05\x36\x62\x6e\xd9\xbc\xfb\x63\xc6\x79\x89\x3c\x90\x89\x2b\xd1\x8c"[..],
5013            &b"\xe0\xc2\x54\xc7\xd6\xb4\xe8\x9e\x96\x55\x6e\x7b\xd5\x7f\xac\xd4\xa7\x1c"[..],
5014            &b"\xa0\xdf\x01\x30\xad\xc0\x9f\x69\x06\x10\x43\x7f\xf4\x5d\x62\xa3\xea\x73"[..],
5015            &b"\xf2\x14\x79\x19\x13\xea\x59\x14\x79\xa8\xe7\xce\xce\x44\x25\x13\x41\x18"[..],
5016            &b"\x57\xdd\xce\xe4\xbe\xcc\x20\x80\x29\x71\x73\xa7\x7c\x86\x39\x76\xf4\xa7"[..],
5017            &b"\x1c\x63\x24\x21\x93\x1e\xb5\x9a\x5c\x8a\x9e\xda\x8b\x9d\x88\x97\xfc\x98"[..],
5018            &b"\x7d\x26\x74\x04\x1f\xa8\x10\x4f\x45\xcd\x46\xe8\x28\xe4\x8e\x59\x67\x63"[..],
5019            &b"\x4a\xcf\x1e\xed\xdd\xbb\x79\x2f\x8d\x94\xab\xfc\xdb\xc5\x79\x1a\x4d\xcd"[..],
5020            &b"\x53\x41\xdf\xd1\x7a\x8f\x46\x3e\x1f\x79\x88\xe3\xee\x9f\xc4\xc1\xe6\x2e"[..],
5021            &b"\x89\x4d\x28\xc9\xca\x28\xc2\x0a\xc5\xc7\xf1\x22\xcd\xb3\x36\xfa\xe3\x7e"[..],
5022            &b"\xa6\xcd\x95\x55\x5e\x0e\x1a\x75\x7f\x65\x27\xd3\x37\x4f\x23\xc5\xab\x49"[..],
5023            &b"\x68\x4e\x02\xb5\xbf\xd7\x95\xc0\x78\x67\xbc\x1a\xe9\xae\x6f\x44\x58\x8a"[..],
5024            &b"\xc2\xce\x42\x98\x4e\x77\xc7\x2a\xa0\xa7\x7d\xe4\x3b\xd1\x20\x82\x1a\xd3"[..],
5025            &b"\xe2\xc7\x76\x5d\x06\x46\xb5\x24\xd7\xfb\x57\x63\x2b\x19\x51\x48\x65\x6d"[..],
5026            &b"\xfb\xe0\x98\xd1\x14\x0e\x17\x64\x29\x34\x6f\x6e\x66\x9e\x8d\xc9\x89\x49"[..],
5027            &b"\x69\xee\x74\xf3\x35\xe6\x8b\x67\x56\x95\x7f\x1b\xe9\xed\x8c\x0f\xe2\x19"[..],
5028            &b"\x59\xbf\x03\x35\x55\x3c\x04\xbc\x40\x52\x90\x10\x08\xad\xa7\x65\xe0\x31"[..],
5029            &b"\xcb\xcf\x3d\xd4\x62\x68\x01\x0d\xed\xf5\x28\x64\x2d\xaa\x7c\x99\x15\x8d"[..],
5030            &b"\x70\x32\x53\xb8\x9d\x0a\x3c\xbf\x91\x02\x04\xd0\xee\x87\xce\x04\xcc\x3e"[..],
5031            &b"\xa8\x20\xfd\x97\xdf\xbf\x4a\xbc\xfc\xc9\x7c\x77\x21\xcc\x23\x6f\x59\x38"[..],
5032            &b"\xd8\xd9\xa0\x0e\xb1\x23\x4e\x04\x3f\x14\x9e\xcc\x05\x54\xab\x20\x69\xed"[..],
5033            &b"\xa4\xd5\x1d\xb4\x1b\x52\xed\x6a\xea\xeb\x7f\xd1\xbc\xfd\x75\x20\xa0\x1c"[..],
5034            &b"\x59\x8c\x5a\xa1\x2a\x70\x64\x11\xb1\x7b\xc1\x24\x80\x28\x51\x4c\x94\xa1"[..],
5035            &b"\x95\x64\x72\xe8\x90\x67\x38\x74\x2b\xab\x38\x46\x12\x71\xce\x19\x98\x98"[..],
5036            &b"\xf7\x89\xd4\xfe\x2f\x2a\xc5\x61\x20\xd0\xa4\x1a\x51\x3c\x82\xc8\x18\x31"[..],
5037            &b"\x7a\x10\xe8\x1c\xc6\x95\x5a\xa0\x82\x88\xce\x8f\x4b\x47\x85\x7e\x89\x95"[..],
5038            &b"\x95\x52\x1e\xac\xce\x45\x57\x61\x38\x97\x2b\x62\xa5\x14\x6f\xc3\xaa\x6c"[..],
5039            &b"\x35\x83\xc9\xa3\x1e\x30\x89\xf4\xb1\xea\x4f\x39\xde\xde\xc7\x46\x5c\x0e"[..],
5040            &b"\x85\x41\xec\x6a\xa4\xcb\xee\x70\x9c\x57\xd9\xf4\xa1\xc3\x9c\x2a\x0a\xf0"[..],
5041            &b"\x5d\x58\xb0\xae\xd4\xdc\xc5\x6a\xa8\x34\xfa\x23\xef\xef\x08\x39\xc3\x3d"[..],
5042            &b"\xea\x11\x6e\x6a\xe0\x1e\xd0\x52\xa8\xc3\x6e\xc9\x1c\xfc\xd0\x0c\x4c\xea"[..],
5043            &b"\x0d\x82\xcb\xdd\x29\x1a\xc4\x4f\x6e\xa3\x4d\xcb\x7a\x38\x77\xe5\x15\x6e"[..],
5044            &b"\xad\xfa\x9d\x2f\x02\xb6\x39\x84\x3a\x60\x8f\x71\x9f\x92\xe5\x24\x4f\xbd"[..],
5045            &b"\x18\x49\xd5\xef\xbf\x70\xfb\xd1\x4c\x2e\xfc\x2f\x36\xf3\x00\x31\x2e\x90"[..],
5046            &b"\x18\xcc\xf4\x71\xb9\xe4\xf9\xbe\xcb\x5e\xff\xf3\xe7\xf8\xca\x03\x60\x66"[..],
5047            &b"\xb3\xc9\x5a\xf9\x74\x09\x02\x57\xb6\x90\x94\xfc\x41\x35\xdc\x35\x3f\x32"[..],
5048            &b"\x7a\xa6\xa5\xcd\x8a\x8f\xc8\x3d\xc8\x81\xc3\xec\x37\x74\x86\x61\x41\x0d"[..],
5049            &b"\xc5\xe2\xc8\x0c\x84\x2b\x3b\x71\x58\xde\x1b\xe3\x20\x65\x2e\x76\xf4\x98"[..],
5050            &b"\xd8\xaa\x78\xe6\xeb\xb8\x85\x0d\xa0\xd0\xf5\x57\x64\x01\x58\x55\x82\xd5"[..],
5051            &b"\x0f\x2d\x9c\x3e\x2a\xa0\x7e\xaf\x42\xf3\x37\xd1\xb3\xaf\xda\x5b\xa9\xda"[..],
5052            &b"\xe3\x89\x5d\xf1\xca\xa5\x12\x3d\xe7\x91\x95\x53\x21\x72\xca\x7f\xf6\x79"[..],
5053            &b"\x59\x21\xcf\x30\x18\xfb\x78\x55\x40\x59\xc3\xf9\xf1\xdd\x58\x44\x5e\x83"[..],
5054            &b"\x11\x5c\x2d\x1d\x91\xf6\x01\x3d\x3f\xd4\x33\x81\x66\x6c\x40\x7a\x9d\x70"[..],
5055            &b"\x10\x58\xe6\x53\xad\x85\x11\x99\x3e\x4b\xbc\x31\xc6\x78\x9d\x79\xc5\xde"[..],
5056            &b"\x9f\x2e\x43\xfa\x76\x84\x2f\xfd\x28\x75\x12\x48\x25\xfd\x15\x8c\x29\x6a"[..],
5057            &b"\x91\xa4\x63\xc0\xa2\x8c\x41\x3c\xf1\xb0\xf8\xdf\x66\xeb\xbd\x14\x88\xa9"[..],
5058            &b"\x81\xa7\x35\xc4\x41\x40\x6c\x10\x3f\x09\xbd\xb5\xd3\x7a\xee\x4b\xd5\x86"[..],
5059            &b"\xff\x36\x03\x6b\x78\xde"[..],
5060        ].concat(),
5061        b"\x62\x01\x53\x8a\xe9\x25\xe1\x06\x09\x8e\xba\x12\x74\x87\x09\x9a\x95\xe4\x86\x62\
5062          \x2b\x4b\xf9\xa6\x2e\x7b\x35\x43\xf7\x39\x99\x0f\x3b\x6f\xfd\x1a\x6e\x23\x54\x70\
5063          \xb5\x1d\x10\x1c\x63\x40\x96\x99\x41\xb6\x96\x0b\x70\x98\xec\x17\xb0\xaa\xdc\x4a\
5064          \xab\xe8\x3b\xb7\x6b\x00\x1c\x5b\xc3\xe0\xa2\x8b\x7c\x17\xc8\x92\xc9\xb0\x92\xb6\
5065          \x70\x84\x95\x30".to_vec(),
5066        b"\x4e\x01\xe5\x04\x35\xac\x00\x00\x80".to_vec(),
5067        b"\x62\x01\x41\xb0\x75\x5c\x27\x46\xef\x8a\xe7\x1d\x50\x38\xb2\x13\x33\xe0\x79\x35\
5068          \x1b\xc2\xb5\x79\x73\xe7\xc2\x6f\xb9\x1a\x8c\x21\x0e\xa9\x54\x17\x6c\x41\xab\xc8\
5069          \x16\x57\xec\x5e\xeb\x89\x3b\xa9\x90\x8c\xff\x4d\x46\x8b\xf0\xd9\xc0\xd0\x51\xcf\
5070          \x8b\x88\xf1\x5f\x1e\x9e\xc1\xb9\x1f\xe3\x06\x45\x35\x8a\x47\xe8\x9a\xf2\x4f\x19\
5071          \x4c\xf8\xce\x68\x1b\x63\x34\x11\x75\xea\xe5\xb1\x0f\x38\xcc\x05\x09\x8b\x3e\x2b\
5072          \x88\x84\x9d\xc5\x03\xc3\xc0\x90\x32\xe2\x45\x69\xb1\xe5\xf7\x68\x6b\x16\x90\xa0\
5073          \x40\xe6\x18\x74\xd8\x68\xf3\x34\x38\x99\xf2\x6c\xb7\x1a\x35\x21\xca\x52\x56\x4c\
5074          \x7f\xb2\xa3\xd5\xb8\x40\x50\x48\x3e\xdc\xdf\x0b\xf5\x54\x5a\x15\x1a\xe2\xc3\xb4\
5075          \x94\xda\x3f\xb5\x34\xa2\xca\xbc\x2f\xe0\xa4\xe5\x69\xf4\xbf\x62\x4d\x15\x21\x1b\
5076          \x11\xfc\x39\xaa\x86\x74\x96\x63\xfd\x07\x53\x26\xf6\x34\x72\xeb\x14\x37\x98\x0d\
5077          \xf4\x68\x91\x2c\x6b\x46\x83\x88\x82\x04\x8b\x9f\xb8\x32\x73\x75\x8b\xf9\xac\x71\
5078          \x42\xd1\x2d\xb4\x28\x28\xf5\x78\xe0\x32\xf3\xe1\xfc\x43\x6b\xf9\x92\xf7\x48\xfe\
5079          \x7f\xc0\x17\xbd\xfd\xba\x2f\x58\x6f\xee\x84\x03\x18\xce\xb0\x9d\x8d\xeb\x22\xf1\
5080          \xfc\xb1\xcf\xff\x2f\xb2\x9f\x6c\xe5\xb4\x69\xdc\xdd\x20\x93\x00\x30\xad\x56\x04\
5081          \x66\x7e\xa3\x3c\x18\x4b\x43\x66\x00\x27\x1e\x1c\x09\x11\xd8\xf4\x8a\x9e\xc5\x6a\
5082          \x94\xe5\xae\x0b\x8a\xbe\x84\xda\xe5\x44\x7f\x38\x1c\xe7\xbb\x03\x19\x66\xe1\x5d\
5083          \x1d\xc1\xbd\x3d\xc6\xb7\xe3\xff\x7f\x8e\xff\x1e\xf6\x9e\x6f\x58\x27\x74\x65\xef\
5084          \x02\x5d\xa4\xde\x27\x7f\x51\xe3\x4b\x9e\x3f\x79\x83\xbd\x1b\x8f\x0d\x77\xfb\xbc\
5085          \xc5\x9f\x15\xa7\x4e\x05\x8a\x24\x97\x66\xb2\x7c\xf6\xe1\x84\x54\xdb\x39\x5e\xf6\
5086          \x1b\x8f\x05\x73\x1d\xb6\x8e\xd7\x09\x9a\xc5\x92\x80".to_vec(),
5087    ];
5088
5089            for cur in tests {
5090                let mut pck = H265Depacketizer::default();
5091                let mut out = Vec::new();
5092                let mut extra = CodecExtra::None;
5093                let _ = pck.depacketize(&cur, &mut out, &mut extra)?;
5094            }
5095
5096            Ok(())
5097        }
5098
5099        /// Test aggregated packets match exact payload layout.
5100        /// Verifies AP packet structure: [AP_Header (2)] [Size1 (2)] [NAL1] [Size2 (2)] [NAL2].
5101        #[test]
5102        fn test_h265_aggregated_exact_layout() -> Result<()> {
5103            let mut packetizer = H265Packetizer::default();
5104
5105            // Create two identical simple NAL units
5106            let header = H265NALUHeader::new(0x02, 0x01); // Type 1, layer_id=0, tid=1
5107            let payload = vec![0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff];
5108
5109            let mut nalu = vec![header.0 as u8, (header.0 >> 8) as u8];
5110            nalu.extend(&payload);
5111
5112            // Cache NAL units (parameter sets or similar)
5113            let vps = vec![0x40, 0x01, 0xAA];
5114            let sps = vec![0x42, 0x01, 0xBB];
5115
5116            packetizer.packetize(100, &vps)?;
5117            packetizer.packetize(100, &sps)?;
5118
5119            // Trigger aggregation
5120            let packets = packetizer.packetize(100, &nalu)?;
5121
5122            if packets.len() == 1 {
5123                // If AP was created, verify structure
5124                let ap = &packets[0];
5125                let ap_header = H265NALUHeader::new(ap[0], ap[1]);
5126
5127                if ap_header.nalu_type() == H265NALU_AGGREGATION_PACKET_TYPE {
5128                    // AP structure verified
5129                    assert_eq!(ap_header.nalu_type(), H265NALU_AGGREGATION_PACKET_TYPE);
5130                }
5131            }
5132
5133            Ok(())
5134        }
5135
5136        /// Regression test for PACI packet with payload smaller than H265NALU_HEADER_SIZE.
5137        /// Previously this would panic with "index out of bounds" when accessing payload[1].
5138        #[test]
5139        fn test_paci_short_payload_no_panic() -> Result<()> {
5140            // Create a PACI packet with a single-byte payload
5141            // Type 50 = PACI packet
5142            let paci_packet: Vec<u8> = vec![
5143                0x64, 0x01, // PayloadHdr: Type=50 (PACI), TID=1
5144                0x00, 0x00, // PACI header fields: A=0, cType=0, PHSsize=0
5145                0xAB, // Single byte payload (less than H265NALU_HEADER_SIZE)
5146            ];
5147
5148            let mut depacketizer = H265Depacketizer::default();
5149            let mut out = Vec::new();
5150            let mut extra = CodecExtra::None;
5151
5152            // This should NOT panic - the fix checks payload.len() >= H265NALU_HEADER_SIZE
5153            let result = depacketizer.depacketize(&paci_packet, &mut out, &mut extra);
5154            assert!(result.is_ok());
5155
5156            // Output should contain the PACI payload with Annex-B start code
5157            assert!(out.starts_with(ANNEXB_NALUSTART_CODE));
5158            assert_eq!(out.len(), ANNEXB_NALUSTART_CODE.len() + 1); // start code + 1 byte payload
5159
5160            Ok(())
5161        }
5162    } // end integration_tests
5163
5164    #[test]
5165    fn test_detect_h265_keyframe() {
5166        // Empty / too short payload
5167        assert!(!detect_h265_keyframe(&[]));
5168        assert!(!detect_h265_keyframe(&[0x00]));
5169
5170        // Single IDR_W_RADL (type 19): nalu_type in bits [14:9]
5171        // type 19 = 0b010011 → byte0 = 0b0_010011_0 = 0x26, byte1 = TID
5172        let idr_w_radl = H265NALUHeader::new_with_type(H265NALU_IDR_W_RADL, 0, 1);
5173        assert!(detect_h265_keyframe(&idr_w_radl.0.to_be_bytes()));
5174
5175        // Single IDR_N_LP (type 20)
5176        let idr_n_lp = H265NALUHeader::new_with_type(H265NALU_IDR_N_LP, 0, 1);
5177        assert!(detect_h265_keyframe(&idr_n_lp.0.to_be_bytes()));
5178
5179        // Single CRA (type 21)
5180        let cra = H265NALUHeader::new_with_type(H265NALU_CRA_NUT, 0, 1);
5181        assert!(detect_h265_keyframe(&cra.0.to_be_bytes()));
5182
5183        // Single BLA_W_LP (type 16)
5184        let bla = H265NALUHeader::new_with_type(H265NALU_BLA_W_LP, 0, 1);
5185        assert!(detect_h265_keyframe(&bla.0.to_be_bytes()));
5186
5187        // Single non-IRAP (type 1 = TRAIL_R)
5188        let trail_r = H265NALUHeader::new_with_type(1, 0, 1);
5189        assert!(!detect_h265_keyframe(&trail_r.0.to_be_bytes()));
5190
5191        // Aggregation packet (type 48) with IDR inside
5192        let ap_header = H265NALUHeader::new_with_type(H265NALU_AGGREGATION_PACKET_TYPE, 0, 1);
5193        let idr_header = H265NALUHeader::new_with_type(H265NALU_IDR_W_RADL, 0, 1);
5194        let idr_bytes = idr_header.0.to_be_bytes();
5195        let mut ap_with_idr = Vec::new();
5196        ap_with_idr.extend_from_slice(&ap_header.0.to_be_bytes()); // AP header
5197        ap_with_idr.extend_from_slice(&[0x00, 0x03]); // NALU size = 3
5198        ap_with_idr.extend_from_slice(&idr_bytes); // IDR header
5199        ap_with_idr.push(0x00); // payload byte
5200        assert!(detect_h265_keyframe(&ap_with_idr));
5201
5202        // Aggregation packet without IRAP
5203        let non_irap_header = H265NALUHeader::new_with_type(1, 0, 1);
5204        let non_irap_bytes = non_irap_header.0.to_be_bytes();
5205        let mut ap_no_irap = Vec::new();
5206        ap_no_irap.extend_from_slice(&ap_header.0.to_be_bytes());
5207        ap_no_irap.extend_from_slice(&[0x00, 0x03]);
5208        ap_no_irap.extend_from_slice(&non_irap_bytes);
5209        ap_no_irap.push(0x00);
5210        assert!(!detect_h265_keyframe(&ap_no_irap));
5211
5212        // FU start fragment with IDR type
5213        let fu_header_bytes = H265NALUHeader::new_with_type(H265NALU_FRAGMENTATION_UNIT_TYPE, 0, 1);
5214        let mut fu_start_idr = Vec::new();
5215        fu_start_idr.extend_from_slice(&fu_header_bytes.0.to_be_bytes());
5216        fu_start_idr.push(0x80 | H265NALU_IDR_W_RADL); // S=1, type=19
5217        fu_start_idr.extend_from_slice(&[0x00, 0x00]);
5218        assert!(detect_h265_keyframe(&fu_start_idr));
5219
5220        // FU continuation fragment (S=0) - cannot detect
5221        let mut fu_cont = Vec::new();
5222        fu_cont.extend_from_slice(&fu_header_bytes.0.to_be_bytes());
5223        fu_cont.push(H265NALU_IDR_W_RADL); // S=0, type=19
5224        fu_cont.extend_from_slice(&[0x00, 0x00]);
5225        assert!(!detect_h265_keyframe(&fu_cont));
5226
5227        // FU too short (no FU header byte)
5228        assert!(!detect_h265_keyframe(&fu_header_bytes.0.to_be_bytes()));
5229    }
5230
5231    #[test]
5232    fn packetize_respects_mtu() -> Result<()> {
5233        // 2-byte NAL header (non-parameter-set type) + payload.
5234        let mut nalu = vec![0x02u8, 0x01];
5235        nalu.extend(std::iter::repeat(0xABu8).take(2000));
5236        for &mtu in &[100usize, 300, 600, 1200] {
5237            let mut p = H265Packetizer::default();
5238            let pkts = p.packetize(mtu, &nalu)?;
5239            assert!(!pkts.is_empty(), "H265 produced no packets at mtu {mtu}");
5240            for (i, pkt) in pkts.iter().enumerate() {
5241                assert!(
5242                    pkt.len() <= mtu,
5243                    "H265 packet {i} size {} > mtu {mtu}",
5244                    pkt.len()
5245                );
5246            }
5247        }
5248        Ok(())
5249    }
5250} // end test module