Skip to main content

rtci_rtp/codec/h265/
mod.rs

1//! H.265/HEVC RTP payload format ([RFC 7798]).
2//!
3//! HEVC differs from H.264 in ways that matter to packetization: NAL headers are two bytes
4//! rather than one, and there is an extra aggregation form (PACI) that can carry payload
5//! content information ahead of the NAL unit.
6//!
7//! This module provides the three packet shapes the RFC defines — single NAL unit,
8//! aggregation, and fragmentation unit — plus [`HevcPayloader`](crate::codec::h265::HevcPayloader), which picks between them
9//! based on the MTU, and the depacketizer that reverses the choice.
10//!
11//! [RFC 7798]: https://datatracker.ietf.org/doc/html/rfc7798
12
13use bytes::{BufMut, Bytes, BytesMut};
14
15use super::h264::{ANNEXB_NALUSTART_CODE, annex_b_nal_units, don_diff};
16use crate::packetizer::{Depacketizer, Payloader};
17use shared::error::{Error, Result};
18
19#[cfg(test)]
20mod h265_test;
21#[cfg(test)]
22mod partition_head_test;
23#[cfg(test)]
24mod rfc7798_test;
25#[cfg(test)]
26mod short_nal_test;
27
28/// The three-byte Annex B start code (`00 00 01`).
29pub static ANNEXB_3_NALUSTART_CODE: Bytes = Bytes::from_static(&[0x00, 0x00, 0x01]);
30/// Payload header for a single NAL unit packet.
31pub static SING_PAYLOAD_HDR: Bytes = Bytes::from_static(&[0x1C, 0x01]);
32/// Payload header for an aggregation packet.
33pub static AGGR_PAYLOAD_HDR: Bytes = Bytes::from_static(&[0x60, 0x01]);
34/// Payload header for a fragmentation unit.
35pub static FRAG_PAYLOAD_HDR: Bytes = Bytes::from_static(&[0x62, 0x01]);
36/// FU header for the first fragment of an IDR frame.
37pub static FU_HDR_IDR_S: u8 = 0x93;
38/// FU header for a middle fragment of an IDR frame.
39pub static FU_HDR_IDR_M: u8 = 0x13;
40/// FU header for the last fragment of an IDR frame.
41pub static FU_HDR_IDR_E: u8 = 0x53;
42/// FU header for the first fragment of a P frame.
43pub static FU_HDR_P_S: u8 = 0x81;
44/// FU header for a middle fragment of a P frame.
45pub static FU_HDR_P_M: u8 = 0x01;
46/// FU header for the last fragment of a P frame.
47pub static FU_HDR_P_E: u8 = 0x41;
48/// FU header for the first fragment of a B frame.
49pub static FU_HDR_B_S: u8 = 0x80;
50/// FU header for a middle fragment of a B frame.
51pub static FU_HDR_B_M: u8 = 0x00;
52/// FU header for the last fragment of a B frame.
53pub static FU_HDR_B_E: u8 = 0x40;
54/// The payload MTU this payloader targets, chosen to survive typical paths without IP
55/// fragmentation.
56pub const RTP_OUTBOUND_MTU: usize = 1200;
57/// Bytes of FU header following the payload header in a fragmentation unit.
58pub const H265FRAGMENTATION_UNIT_HEADER_SIZE: usize = 1;
59/// Bytes in an H.265 NAL header — two, unlike H.264's one.
60pub const NAL_HEADER_SIZE: usize = 2;
61
62#[derive(PartialEq, Hash, Debug, Copy, Clone)]
63/// The H.265 NAL unit types this payloader distinguishes.
64#[non_exhaustive]
65pub enum UnitType {
66    /// Video parameter set.
67    VPS = 32,
68    /// Sequence parameter set.
69    SPS = 33,
70    /// Picture parameter set.
71    PPS = 34,
72    /// Clean random access picture — a keyframe that allows mid-stream tune-in.
73    CRA = 21,
74    /// Supplemental enhancement information.
75    SEI = 39,
76    /// Instantaneous decoder refresh picture — a keyframe.
77    IDR = 19,
78    /// A predicted (P) frame.
79    PFR = 1,
80    /// A bidirectionally predicted (B) frame.
81    BFR = 0,
82    /// A unit type this payloader skips.
83    IGNORE = -1,
84}
85impl UnitType {
86    /// Maps a raw NAL type id to a [`UnitType`].
87    ///
88    /// # Errors
89    ///
90    /// Fails if the id is not one this payloader handles.
91    pub fn for_id(id: u8) -> Result<UnitType> {
92        if id > 64 {
93            Err(Error::ErrUnhandledNaluType)
94        } else {
95            let t = match id {
96                32 => UnitType::VPS,
97                33 => UnitType::SPS,
98                34 => UnitType::PPS,
99                21 => UnitType::CRA,
100                39 => UnitType::SEI,
101                19 => UnitType::IDR,
102                1 => UnitType::PFR,
103                0 => UnitType::BFR,
104                _ => UnitType::IGNORE, // shouldn't happen
105            };
106            Ok(t)
107        }
108    }
109}
110
111/// Largest NAL unit reassembled from fragmentation units. Far above any real slice; a
112/// reassembly that would grow past it is dropped.
113pub const MAX_H265_FU_NALU_SIZE: usize = 4 * 1024 * 1024;
114/// The de-packetization buffer never holds more NAL units than this, whatever
115/// `sprop-depack-buf-nalus` and `sprop-max-don-diff` ask for.
116pub const MAX_DEPACKETIZATION_NAL_UNITS: usize = 4096;
117/// Nor more bytes than this.
118pub const MAX_DEPACKETIZATION_BYTES: usize = 32 * 1024 * 1024;
119
120#[derive(Default, Debug, Clone)]
121/// Packetizes H.265/HEVC NAL units into RTP payloads, fragmenting when needed.
122///
123/// By default the stream is one with `sprop-max-don-diff` equal to 0: no decoding order
124/// numbers, NAL units in decoding order. [`HevcPayloader::with_donl`] makes one for a stream
125/// whose `sprop-max-don-diff` is greater than 0, where every packet carries them (RFC 7798
126/// sections 4.4.1 to 4.4.3).
127pub struct HevcPayloader {
128    /// `sprop-max-don-diff` > 0: DONL and DOND fields are written.
129    donl: bool,
130    /// The decoding order number of the next NAL unit.
131    next_don: u16,
132}
133
134impl HevcPayloader {
135    /// A payloader for a stream whose `sprop-max-don-diff` is greater than 0: single NAL unit
136    /// packets and the first fragment of a NAL unit carry a DONL, and aggregation packets a
137    /// DONL for their first unit and a DOND for each other one (RFC 7798 sections 4.4.1 to
138    /// 4.4.3). NAL units are sent in the order given, which is decoding order, numbered from
139    /// `initial_don` upwards by one, so every DOND is 0.
140    pub fn with_donl(initial_don: u16) -> Self {
141        HevcPayloader {
142            donl: true,
143            next_don: initial_don,
144        }
145    }
146
147    /// The NAL units of an access unit that are sent: those with a whole two-byte header whose
148    /// type is a NAL unit type (below 48; 48 to 50 are this format's packet types, and they
149    /// are neither aggregated, fragmented nor nested: RFC 7798 sections 4.4.2 to 4.4.4).
150    fn sendable_nal_units(payload: &Bytes) -> Vec<Bytes> {
151        annex_b_nal_units(payload)
152            .into_iter()
153            .filter(|nalu| {
154                nalu.len() >= NAL_HEADER_SIZE
155                    && H265NALUHeader::new(nalu[0], nalu[1]).nalu_type()
156                        < H265NALU_AGGREGATION_PACKET_TYPE
157            })
158            .collect()
159    }
160
161    /// The packets of a stream with decoding order numbers.
162    fn payload_with_don(&mut self, mtu: usize, payload: &Bytes) -> Vec<Bytes> {
163        const DONL_SIZE: usize = 2;
164        const DOND_SIZE: usize = 1;
165
166        fn flush(pending: &mut Vec<(u16, Bytes)>, payloads: &mut Vec<Bytes>) {
167            let nalus: Vec<Bytes> = pending.iter().map(|(_, nalu)| nalu.clone()).collect();
168            match pending.len() {
169                0 => {}
170                1 => {
171                    // A single NAL unit packet: the NAL unit header, DONL, the rest.
172                    let (don, nalu) = &pending[0];
173                    let mut out = BytesMut::with_capacity(nalu.len() + DONL_SIZE);
174                    out.extend_from_slice(&nalu[..NAL_HEADER_SIZE]);
175                    out.put_u16(*don);
176                    out.extend_from_slice(&nalu[NAL_HEADER_SIZE..]);
177                    payloads.push(out.freeze());
178                }
179                _ => {
180                    let mut out = BytesMut::new();
181                    out.extend_from_slice(&HevcPayloader::aggregation_payload_header(&nalus));
182                    let mut previous = pending[0].0;
183                    for (i, (don, nalu)) in pending.iter().enumerate() {
184                        if i == 0 {
185                            out.put_u16(*don);
186                        } else {
187                            // DON = previous DON + DOND + 1.
188                            out.put_u8(don.wrapping_sub(previous).wrapping_sub(1) as u8);
189                        }
190                        previous = *don;
191                        out.put_u16(nalu.len() as u16);
192                        out.extend_from_slice(nalu);
193                    }
194                    payloads.push(out.freeze());
195                }
196            }
197            pending.clear();
198        }
199
200        let mut payloads = vec![];
201        let mut pending: Vec<(u16, Bytes)> = vec![];
202        let mut pending_size = 0;
203        for nalu in Self::sendable_nal_units(payload) {
204            let don = self.next_don;
205            self.next_don = self.next_don.wrapping_add(1);
206
207            if nalu.len() + DONL_SIZE > mtu || nalu.len() > u16::MAX as usize {
208                flush(&mut pending, &mut payloads);
209                // Fragmentation units: the first carries the DONL.
210                let header = H265NALUHeader::new(nalu[0], nalu[1]);
211                let data = &nalu[NAL_HEADER_SIZE..];
212                let fu_header_size = NAL_HEADER_SIZE + H265FRAGMENTATION_UNIT_HEADER_SIZE;
213                let (Some(first_size), Some(next_size)) = (
214                    mtu.checked_sub(fu_header_size + DONL_SIZE)
215                        .filter(|&size| size > 0),
216                    mtu.checked_sub(fu_header_size).filter(|&size| size > 0),
217                ) else {
218                    continue;
219                };
220                // Never one FU, and no FU with an empty payload: a NAL unit that would fit
221                // the first fragment is cut in two.
222                let first_len = if data.len() <= first_size {
223                    data.len().div_ceil(2)
224                } else {
225                    first_size
226                };
227                let (first, rest) = data.split_at(first_len);
228                if first.is_empty() || rest.is_empty() {
229                    continue;
230                }
231                let mut out = BytesMut::with_capacity(fu_header_size + DONL_SIZE + first.len());
232                out.extend_from_slice(&Self::fragmentation_payload_header(header));
233                out.put_u8(Self::fu_header(header.nalu_type(), true, false));
234                out.put_u16(don);
235                out.extend_from_slice(first);
236                payloads.push(out.freeze());
237                let last = rest.len().div_ceil(next_size) - 1;
238                for (i, fragment) in rest.chunks(next_size).enumerate() {
239                    let mut out = BytesMut::with_capacity(fu_header_size + fragment.len());
240                    out.extend_from_slice(&Self::fragmentation_payload_header(header));
241                    out.put_u8(Self::fu_header(header.nalu_type(), false, i == last));
242                    out.extend_from_slice(fragment);
243                    payloads.push(out.freeze());
244                }
245                continue;
246            }
247
248            let first_unit_size = DONL_SIZE + 2 + nalu.len();
249            let next_unit_size = DOND_SIZE + 2 + nalu.len();
250            if pending.is_empty() {
251                pending_size = NAL_HEADER_SIZE + first_unit_size;
252            } else if pending_size + next_unit_size > mtu {
253                flush(&mut pending, &mut payloads);
254                pending_size = NAL_HEADER_SIZE + first_unit_size;
255            } else {
256                pending_size += next_unit_size;
257            }
258            pending.push((don, nalu));
259        }
260        flush(&mut pending, &mut payloads);
261        payloads
262    }
263
264    fn aggregation_payload_header(nalus: &[Bytes]) -> [u8; 2] {
265        let mut f = false;
266        let mut layer_id = u8::MAX;
267        let mut tid = u8::MAX;
268
269        for nalu in nalus {
270            let header = H265NALUHeader::new(nalu[0], nalu[1]);
271            f |= header.f();
272            layer_id = layer_id.min(header.layer_id());
273            tid = tid.min(header.tid());
274        }
275
276        let mut raw = (H265NALU_AGGREGATION_PACKET_TYPE as u16) << 9;
277        raw |= (layer_id as u16) << 3;
278        raw |= tid as u16;
279        if f {
280            raw |= 1 << 15;
281        }
282
283        raw.to_be_bytes()
284    }
285
286    fn fragmentation_payload_header(payload_header: H265NALUHeader) -> [u8; 2] {
287        let mut raw = (H265NALU_FRAGMENTATION_UNIT_TYPE as u16) << 9;
288        raw |= (payload_header.layer_id() as u16) << 3;
289        raw |= payload_header.tid() as u16;
290        if payload_header.f() {
291            raw |= 1 << 15;
292        }
293
294        raw.to_be_bytes()
295    }
296
297    fn fu_header(nalu_type: u8, is_first: bool, is_last: bool) -> u8 {
298        let mut header = nalu_type & 0b0011_1111;
299        if is_first {
300            header |= 0b1000_0000;
301        } else if is_last {
302            header |= 0b0100_0000;
303        }
304        header
305    }
306
307    /// Locates the NAL unit boundaries in an Annex B buffer.
308    ///
309    /// Returns the offset of each start code and the length of the code that was matched:
310    /// four-byte codes, or three-byte codes when there is no four-byte one. A stream that
311    /// mixes the two is not split right by this; the payloader does not use it.
312    pub fn parse(nalu: &Bytes) -> (Vec<usize>, usize) {
313        let finder = memchr::memmem::Finder::new(&ANNEXB_NALUSTART_CODE);
314        let nals = finder.find_iter(nalu).collect::<Vec<usize>>();
315        if nals.is_empty() {
316            let finder = memchr::memmem::Finder::new(&ANNEXB_3_NALUSTART_CODE);
317            return (finder.find_iter(nalu).collect::<Vec<usize>>(), 3);
318        }
319        (nals, 4)
320    }
321
322    fn flush_aggregation_buffer(nalus: &mut Vec<Bytes>, mtu: usize, payloads: &mut Vec<Bytes>) {
323        if nalus.is_empty() {
324            return;
325        }
326        if nalus.len() == 1 {
327            payloads.push(nalus.pop().expect("single buffered NAL exists"));
328            return;
329        }
330
331        // Process NALUs in original order: accumulate consecutive normal-sized
332        // NALUs into an AP, but when an oversized NALU (> u16::MAX) is
333        // encountered, flush the current AP first, then emit the oversized
334        // NALU individually (it will be FU-fragmented).
335        //
336        // Defense-in-depth: In practice, payload() sends any nalu.len() > mtu
337        // directly to emit() before it reaches this buffer, so the u16::MAX
338        // branch below is currently unreachable (MTU << u16::MAX). The check
339        // is retained to guard against future callers or MTU changes.
340        let mut pending_normal: Vec<Bytes> = Vec::new();
341
342        for nalu in nalus.drain(..) {
343            if nalu.len() > u16::MAX as usize {
344                // Flush any accumulated normal NALUs as an AP (or single)
345                Self::flush_normal_nalus(&mut pending_normal, mtu, payloads);
346                // Emit the oversized NALU individually via FU fragmentation;
347                // it cannot be placed in an AP because the 16-bit size field would overflow.
348                Self::emit(&nalu, mtu, payloads);
349            } else {
350                pending_normal.push(nalu);
351            }
352        }
353
354        // Flush any remaining normal NALUs
355        Self::flush_normal_nalus(&mut pending_normal, mtu, payloads);
356    }
357
358    /// Flush accumulated normal-sized NALUs: emit a single NALU directly,
359    /// or pack multiple into an aggregation packet.
360    fn flush_normal_nalus(nalus: &mut Vec<Bytes>, mtu: usize, payloads: &mut Vec<Bytes>) {
361        match nalus.len() {
362            0 => {}
363            1 => {
364                payloads.push(nalus.pop().expect("single normal NAL exists"));
365            }
366            _ => {
367                let header = Self::aggregation_payload_header(nalus);
368                let mut aggr_nalu = BytesMut::with_capacity(
369                    NAL_HEADER_SIZE + nalus.iter().map(|nalu| 2 + nalu.len()).sum::<usize>(),
370                );
371                aggr_nalu.extend_from_slice(&header);
372                for nalu in nalus.iter() {
373                    aggr_nalu.extend_from_slice(&(nalu.len() as u16).to_be_bytes());
374                    aggr_nalu.extend_from_slice(nalu);
375                }
376                nalus.clear();
377                if aggr_nalu.len() <= mtu {
378                    payloads.push(aggr_nalu.freeze());
379                }
380            }
381        }
382    }
383
384    fn emit(nalu: &Bytes, mtu: usize, payloads: &mut Vec<Bytes>) {
385        // An H.265 NAL unit header is two bytes (RFC 7798 1.1.4); anything shorter is not one.
386        if nalu.len() < H265NALU_HEADER_SIZE {
387            return;
388        }
389        let payload_header = H265NALUHeader::new(nalu[0], nalu[1]);
390        let payload_nalu_type = payload_header.nalu_type();
391
392        if payload_nalu_type >= H265NALU_AGGREGATION_PACKET_TYPE {
393            return;
394        }
395
396        // Single NALU
397        if nalu.len() <= mtu {
398            payloads.push(nalu.clone());
399            return;
400        }
401        let max_fragment_size =
402            mtu as isize - NAL_HEADER_SIZE as isize - H265FRAGMENTATION_UNIT_HEADER_SIZE as isize;
403        let nalu_data = nalu;
404        let mut nalu_data_index = 2;
405        let nalu_data_length = nalu.len() as isize - nalu_data_index;
406        let mut nalu_data_remaining = nalu_data_length;
407        if std::cmp::min(max_fragment_size, nalu_data_remaining) <= 0 {
408            return;
409        }
410        while nalu_data_remaining > 0 {
411            let current_fragment_size = std::cmp::min(max_fragment_size, nalu_data_remaining);
412            let mut out = BytesMut::with_capacity(
413                NAL_HEADER_SIZE
414                    + H265FRAGMENTATION_UNIT_HEADER_SIZE
415                    + current_fragment_size as usize,
416            );
417            out.extend_from_slice(&Self::fragmentation_payload_header(payload_header));
418            let is_first = nalu_data_index == 2;
419            let is_last = nalu_data_remaining == current_fragment_size;
420            out.put_u8(Self::fu_header(payload_nalu_type, is_first, is_last));
421
422            out.extend_from_slice(
423                &nalu_data
424                    [nalu_data_index as usize..(nalu_data_index + current_fragment_size) as usize],
425            );
426            payloads.push(out.freeze());
427
428            nalu_data_remaining -= current_fragment_size;
429            nalu_data_index += current_fragment_size;
430        }
431    }
432}
433
434impl Payloader for HevcPayloader {
435    /// Payload fragments a H264 packet across one or more byte arrays
436    fn payload(&mut self, mtu: usize, payload: &Bytes) -> Result<Vec<Bytes>> {
437        if payload.is_empty() || mtu == 0 {
438            return Ok(vec![]);
439        }
440
441        if self.donl {
442            return Ok(self.payload_with_don(mtu, payload));
443        }
444
445        let mut payloads = vec![];
446        let mut aggregation_buffer = vec![];
447
448        // The NAL units of the access unit, split at their Annex B start codes of either
449        // length. A buffer without a start code is one NAL unit.
450        for nalu in Self::sendable_nal_units(payload) {
451            if nalu.len() > mtu {
452                Self::flush_aggregation_buffer(&mut aggregation_buffer, mtu, &mut payloads);
453                Self::emit(&nalu, mtu, &mut payloads);
454                continue;
455            }
456
457            let aggregated_size = NAL_HEADER_SIZE
458                + aggregation_buffer
459                    .iter()
460                    .map(|nalu| 2 + nalu.len())
461                    .sum::<usize>()
462                + 2
463                + nalu.len();
464            if !aggregation_buffer.is_empty() && aggregated_size > mtu {
465                Self::flush_aggregation_buffer(&mut aggregation_buffer, mtu, &mut payloads);
466            }
467
468            aggregation_buffer.push(nalu);
469        }
470        Self::flush_aggregation_buffer(&mut aggregation_buffer, mtu, &mut payloads);
471
472        Ok(payloads)
473    }
474
475    fn clone_to(&self) -> Box<dyn Payloader> {
476        Box::new(self.clone())
477    }
478}
479
480///
481/// Network Abstraction Unit Header implementation
482///
483const H265NALU_HEADER_SIZE: usize = 2;
484/// <https://datatracker.ietf.org/doc/html/rfc7798#section-4.4.2>
485const H265NALU_AGGREGATION_PACKET_TYPE: u8 = 48;
486/// <https://datatracker.ietf.org/doc/html/rfc7798#section-4.4.3>
487const H265NALU_FRAGMENTATION_UNIT_TYPE: u8 = 49;
488/// <https://datatracker.ietf.org/doc/html/rfc7798#section-4.4.4>
489const H265NALU_PACI_PACKET_TYPE: u8 = 50;
490
491/// H265NALUHeader is a H265 NAL Unit Header
492///
493/// ```text
494/// +---------------+---------------+
495/// |0|1|2|3|4|5|6|7|0|1|2|3|4|5|6|7|
496/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
497/// |F|   Type    |  layer_id  | tid|
498/// +-------------+-----------------+
499/// ```
500///
501/// ## Specifications
502///
503/// * [RFC 7798 §1.1.4]
504///
505/// [RFC 7798 §1.1.4]: https://tools.ietf.org/html/rfc7798#section-1.1.4
506#[derive(Default, Debug, Copy, Clone, PartialEq, Eq)]
507pub struct H265NALUHeader(pub u16);
508
509impl H265NALUHeader {
510    /// Parses an H.265 NAL header from its two bytes.
511    pub fn new(high_byte: u8, low_byte: u8) -> Self {
512        H265NALUHeader(((high_byte as u16) << 8) | low_byte as u16)
513    }
514
515    /// f is the forbidden bit, should always be 0.
516    pub fn f(&self) -> bool {
517        (self.0 >> 15) != 0
518    }
519
520    /// nalu_type of NAL Unit.
521    pub fn nalu_type(&self) -> u8 {
522        // 01111110 00000000
523        const MASK: u16 = 0b01111110 << 8;
524        ((self.0 & MASK) >> (8 + 1)) as u8
525    }
526
527    /// is_type_vcl_unit returns whether or not the NAL Unit type is a VCL NAL unit.
528    pub fn is_type_vcl_unit(&self) -> bool {
529        // Type is coded on 6 bits
530        const MSB_MASK: u8 = 0b00100000;
531        (self.nalu_type() & MSB_MASK) == 0
532    }
533
534    /// layer_id should always be 0 in non-3D HEVC context.
535    pub fn layer_id(&self) -> u8 {
536        // 00000001 11111000
537        const MASK: u16 = (0b00000001 << 8) | 0b11111000;
538        ((self.0 & MASK) >> 3) as u8
539    }
540
541    /// tid is the temporal identifier of the NAL unit +1.
542    pub fn tid(&self) -> u8 {
543        const MASK: u16 = 0b00000111;
544        (self.0 & MASK) as u8
545    }
546
547    /// is_aggregation_packet returns whether or not the packet is an Aggregation packet.
548    pub fn is_aggregation_packet(&self) -> bool {
549        self.nalu_type() == H265NALU_AGGREGATION_PACKET_TYPE
550    }
551
552    /// is_fragmentation_unit returns whether or not the packet is a Fragmentation Unit packet.
553    pub fn is_fragmentation_unit(&self) -> bool {
554        self.nalu_type() == H265NALU_FRAGMENTATION_UNIT_TYPE
555    }
556
557    /// is_paci_packet returns whether or not the packet is a PACI packet.
558    pub fn is_paci_packet(&self) -> bool {
559        self.nalu_type() == H265NALU_PACI_PACKET_TYPE
560    }
561}
562
563///
564/// Single NAL Unit Packet implementation
565///
566/// H265SingleNALUnitPacket represents a NALU packet, containing exactly one NAL unit.
567///     0                   1                   2                   3
568///    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
569///   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
570///   |           PayloadHdr          |      DONL (conditional)       |
571///   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
572///   |                                                               |
573///   |                  NAL unit payload data                        |
574///   |                                                               |
575///   |                               +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
576///   |                               :...OPTIONAL RTP padding        |
577///   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
578///
579/// ## Specifications
580///
581/// * [RFC 7798 §4.4.1]
582///
583/// [RFC 7798 §4.4.1]: https://tools.ietf.org/html/rfc7798#section-4.4.1
584#[derive(Default, Debug, Clone, PartialEq, Eq)]
585pub struct H265SingleNALUnitPacket {
586    /// payload_header is the header of the H265 packet.
587    payload_header: H265NALUHeader,
588    /// donl is a 16-bit field, that may or may not be present.
589    donl: Option<u16>,
590    /// payload of the fragmentation unit.
591    payload: Bytes,
592
593    might_need_donl: bool,
594}
595
596impl H265SingleNALUnitPacket {
597    /// with_donl can be called to specify whether or not DONL might be parsed.
598    /// DONL may need to be parsed if `sprop-max-don-diff` is greater than 0 on the RTP stream.
599    pub fn with_donl(&mut self, value: bool) {
600        self.might_need_donl = value;
601    }
602
603    /// depacketize parses the passed byte slice and stores the result in the H265SingleNALUnitPacket this method is called upon.
604    fn depacketize(&mut self, payload: &Bytes) -> Result<()> {
605        // A NAL unit may be its two-byte header alone: end of sequence (36), end of
606        // bitstream (37).
607        if payload.len() < H265NALU_HEADER_SIZE {
608            return Err(Error::ErrShortPacket);
609        }
610
611        let payload_header = H265NALUHeader::new(payload[0], payload[1]);
612        if payload_header.f() {
613            return Err(Error::ErrH265CorruptedPacket);
614        }
615        if payload_header.is_fragmentation_unit()
616            || payload_header.is_paci_packet()
617            || payload_header.is_aggregation_packet()
618        {
619            return Err(Error::ErrInvalidH265PacketType);
620        }
621
622        let mut payload = payload.slice(2..);
623
624        if self.might_need_donl {
625            // sizeof(uint16)
626            if payload.len() < 2 {
627                return Err(Error::ErrShortPacket);
628            }
629
630            let donl = ((payload[0] as u16) << 8) | (payload[1] as u16);
631            self.donl = Some(donl);
632            payload = payload.slice(2..);
633        }
634
635        self.payload_header = payload_header;
636        self.payload = payload;
637
638        Ok(())
639    }
640
641    /// payload_header returns the NALU header of the packet.
642    pub fn payload_header(&self) -> H265NALUHeader {
643        self.payload_header
644    }
645
646    /// donl returns the DONL of the packet.
647    pub fn donl(&self) -> Option<u16> {
648        self.donl
649    }
650
651    /// payload returns the Fragmentation Unit packet payload.
652    pub fn payload(&self) -> Bytes {
653        self.payload.clone()
654    }
655}
656
657///
658/// Aggregation Packets implementation
659///
660/// H265AggregationUnitFirst represent the First Aggregation Unit in an AP.
661///
662///    0                   1                   2                   3
663///    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
664///   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
665///                   :       DONL (conditional)      |   NALU size   |
666///   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
667///   |   NALU size   |                                               |
668///   +-+-+-+-+-+-+-+-+         NAL unit                              |
669///   |                                                               |
670///   |                               +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
671///   |                               :
672///   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
673///
674/// ## Specifications
675///
676/// * [RFC 7798 §4.4.2]
677///
678/// [RFC 7798 §4.4.2]: https://tools.ietf.org/html/rfc7798#section-4.4.2
679#[derive(Default, Debug, Clone, PartialEq, Eq)]
680pub struct H265AggregationUnitFirst {
681    donl: Option<u16>,
682    nal_unit_size: u16,
683    nal_unit: Bytes,
684}
685
686impl H265AggregationUnitFirst {
687    /// donl field, when present, specifies the value of the 16 least
688    /// significant bits of the decoding order number of the aggregated NAL
689    /// unit.
690    pub fn donl(&self) -> Option<u16> {
691        self.donl
692    }
693
694    /// nalu_size represents the size, in bytes, of the nal_unit.
695    pub fn nalu_size(&self) -> u16 {
696        self.nal_unit_size
697    }
698
699    /// nal_unit payload.
700    pub fn nal_unit(&self) -> Bytes {
701        self.nal_unit.clone()
702    }
703}
704
705/// H265AggregationUnit represent the an Aggregation Unit in an AP, which is not the first one.
706///
707///    0                   1                   2                   3
708///    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
709///   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
710///                   : DOND (cond)   |          NALU size            |
711///   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
712///   |                                                               |
713///   |                       NAL unit                                |
714///   |                               +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
715///   |                               :
716///   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
717///
718/// ## Specifications
719///
720/// * [RFC 7798 §4.4.2]
721///
722/// [RFC 7798 §4.4.2]: https://tools.ietf.org/html/rfc7798#section-4.4.2
723#[derive(Default, Debug, Clone, PartialEq, Eq)]
724pub struct H265AggregationUnit {
725    dond: Option<u8>,
726    nal_unit_size: u16,
727    nal_unit: Bytes,
728}
729
730impl H265AggregationUnit {
731    /// dond field plus 1 specifies the difference between
732    /// the decoding order number values of the current aggregated NAL unit
733    /// and the preceding aggregated NAL unit in the same AP.
734    pub fn dond(&self) -> Option<u8> {
735        self.dond
736    }
737
738    /// nalu_size represents the size, in bytes, of the nal_unit.
739    pub fn nalu_size(&self) -> u16 {
740        self.nal_unit_size
741    }
742
743    /// nal_unit payload.
744    pub fn nal_unit(&self) -> Bytes {
745        self.nal_unit.clone()
746    }
747}
748
749/// H265AggregationPacket represents an Aggregation packet.
750///   0                   1                   2                   3
751///    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
752///   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
753///   |    PayloadHdr (Type=48)       |                               |
754///   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+                               |
755///   |                                                               |
756///   |             two or more aggregation units                     |
757///   |                                                               |
758///   |                               +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
759///   |                               :...OPTIONAL RTP padding        |
760///   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
761///
762/// ## Specifications
763///
764/// * [RFC 7798 §4.4.2]
765///
766/// [RFC 7798 §4.4.2]: https://tools.ietf.org/html/rfc7798#section-4.4.2
767#[derive(Default, Debug, Clone, PartialEq, Eq)]
768pub struct H265AggregationPacket {
769    first_unit: Option<H265AggregationUnitFirst>,
770    other_units: Vec<H265AggregationUnit>,
771
772    might_need_donl: bool,
773}
774
775impl H265AggregationPacket {
776    /// with_donl can be called to specify whether or not DONL might be parsed.
777    /// DONL may need to be parsed if `sprop-max-don-diff` is greater than 0 on the RTP stream.
778    pub fn with_donl(&mut self, value: bool) {
779        self.might_need_donl = value;
780    }
781
782    /// depacketize parses the passed byte slice and stores the result in the H265AggregationPacket this method is called upon.
783    fn depacketize(&mut self, payload: &Bytes) -> Result<()> {
784        if payload.len() <= H265NALU_HEADER_SIZE {
785            return Err(Error::ErrShortPacket);
786        }
787
788        let payload_header = H265NALUHeader::new(payload[0], payload[1]);
789        if payload_header.f() {
790            return Err(Error::ErrH265CorruptedPacket);
791        }
792        if !payload_header.is_aggregation_packet() {
793            return Err(Error::ErrInvalidH265PacketType);
794        }
795
796        // First parse the first aggregation unit
797        let mut payload = payload.slice(2..);
798        let mut first_unit = H265AggregationUnitFirst::default();
799
800        if self.might_need_donl {
801            if payload.len() < 2 {
802                return Err(Error::ErrShortPacket);
803            }
804
805            let donl = ((payload[0] as u16) << 8) | (payload[1] as u16);
806            first_unit.donl = Some(donl);
807
808            payload = payload.slice(2..);
809        }
810        if payload.len() < 2 {
811            return Err(Error::ErrShortPacket);
812        }
813        first_unit.nal_unit_size = ((payload[0] as u16) << 8) | (payload[1] as u16);
814        payload = payload.slice(2..);
815
816        if payload.len() < first_unit.nal_unit_size as usize {
817            return Err(Error::ErrShortPacket);
818        }
819
820        first_unit.nal_unit = payload.slice(..first_unit.nal_unit_size as usize);
821        payload = payload.slice(first_unit.nal_unit_size as usize..);
822
823        // Parse remaining Aggregation Units
824        let mut units = vec![]; //H265AggregationUnit
825        loop {
826            let mut unit = H265AggregationUnit::default();
827
828            if self.might_need_donl {
829                if payload.is_empty() {
830                    break;
831                }
832
833                let dond = payload[0];
834                unit.dond = Some(dond);
835
836                payload = payload.slice(1..);
837            }
838
839            if payload.len() < 2 {
840                break;
841            }
842            unit.nal_unit_size = ((payload[0] as u16) << 8) | (payload[1] as u16);
843            payload = payload.slice(2..);
844
845            if payload.len() < unit.nal_unit_size as usize {
846                break;
847            }
848
849            unit.nal_unit = payload.slice(..unit.nal_unit_size as usize);
850            payload = payload.slice(unit.nal_unit_size as usize..);
851
852            units.push(unit);
853        }
854
855        // There need to be **at least** two Aggregation Units (first + another one)
856        if units.is_empty() {
857            return Err(Error::ErrShortPacket);
858        }
859
860        self.first_unit = Some(first_unit);
861        self.other_units = units;
862
863        Ok(())
864    }
865
866    /// first_unit returns the first Aggregated Unit of the packet.
867    pub fn first_unit(&self) -> Option<&H265AggregationUnitFirst> {
868        self.first_unit.as_ref()
869    }
870
871    /// other_units returns the all the other Aggregated Unit of the packet (excluding the first one).
872    pub fn other_units(&self) -> &[H265AggregationUnit] {
873        self.other_units.as_slice()
874    }
875}
876
877/// Fragmentation Unit implementation
878///
879/// H265FragmentationUnitHeader is a H265 FU Header
880/// +---------------+
881/// |0|1|2|3|4|5|6|7|
882/// +-+-+-+-+-+-+-+-+
883/// |S|E|  fu_type   |
884/// +---------------+
885#[derive(Default, Debug, Copy, Clone, PartialEq, Eq)]
886pub struct H265FragmentationUnitHeader(pub u8);
887
888impl H265FragmentationUnitHeader {
889    /// s represents the start of a fragmented NAL unit.
890    pub fn s(&self) -> bool {
891        const MASK: u8 = 0b10000000;
892        ((self.0 & MASK) >> 7) != 0
893    }
894
895    /// e represents the end of a fragmented NAL unit.
896    pub fn e(&self) -> bool {
897        const MASK: u8 = 0b01000000;
898        ((self.0 & MASK) >> 6) != 0
899    }
900
901    /// fu_type MUST be equal to the field Type of the fragmented NAL unit.
902    pub fn fu_type(&self) -> u8 {
903        const MASK: u8 = 0b00111111;
904        self.0 & MASK
905    }
906}
907
908/// H265FragmentationUnitPacket represents a single Fragmentation Unit packet.
909///
910///  0                   1                   2                   3
911/// 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
912/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
913/// |    PayloadHdr (Type=49)       |   FU header   | DONL (cond)   |
914/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-|
915/// | DONL (cond)   |                                               |
916/// |-+-+-+-+-+-+-+-+                                               |
917/// |                         FU payload                            |
918/// |                                                               |
919/// |                               +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
920/// |                               :...OPTIONAL RTP padding        |
921/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
922///
923/// ## Specifications
924///
925/// * [RFC 7798 §4.4.3]
926///
927/// [RFC 7798 §4.4.3]: https://tools.ietf.org/html/rfc7798#section-4.4.3
928#[derive(Default, Debug, Clone, PartialEq, Eq)]
929pub struct H265FragmentationUnitPacket {
930    /// payload_header is the header of the H265 packet.
931    payload_header: H265NALUHeader,
932    /// fu_header is the header of the fragmentation unit
933    fu_header: H265FragmentationUnitHeader,
934    /// donl is a 16-bit field, that may or may not be present.
935    donl: Option<u16>,
936    /// payload of the fragmentation unit.
937    payload: Bytes,
938
939    might_need_donl: bool,
940}
941
942impl H265FragmentationUnitPacket {
943    /// with_donl can be called to specify whether or not DONL might be parsed.
944    /// DONL may need to be parsed if `sprop-max-don-diff` is greater than 0 on the RTP stream.
945    pub fn with_donl(&mut self, value: bool) {
946        self.might_need_donl = value;
947    }
948
949    /// depacketize parses the passed byte slice and stores the result in the H265FragmentationUnitPacket this method is called upon.
950    fn depacketize(&mut self, payload: &Bytes) -> Result<()> {
951        const TOTAL_HEADER_SIZE: usize = H265NALU_HEADER_SIZE + H265FRAGMENTATION_UNIT_HEADER_SIZE;
952        if payload.len() <= TOTAL_HEADER_SIZE {
953            return Err(Error::ErrShortPacket);
954        }
955
956        let payload_header = H265NALUHeader::new(payload[0], payload[1]);
957        if payload_header.f() {
958            return Err(Error::ErrH265CorruptedPacket);
959        }
960        if !payload_header.is_fragmentation_unit() {
961            return Err(Error::ErrInvalidH265PacketType);
962        }
963
964        let fu_header = H265FragmentationUnitHeader(payload[2]);
965        let mut payload = payload.slice(3..);
966
967        if fu_header.s() && self.might_need_donl {
968            if payload.len() <= 2 {
969                return Err(Error::ErrShortPacket);
970            }
971
972            let donl = ((payload[0] as u16) << 8) | (payload[1] as u16);
973            self.donl = Some(donl);
974            payload = payload.slice(2..);
975        }
976
977        self.payload_header = payload_header;
978        self.fu_header = fu_header;
979        self.payload = payload;
980
981        Ok(())
982    }
983
984    /// payload_header returns the NALU header of the packet.
985    pub fn payload_header(&self) -> H265NALUHeader {
986        self.payload_header
987    }
988
989    /// fu_header returns the Fragmentation Unit Header of the packet.
990    pub fn fu_header(&self) -> H265FragmentationUnitHeader {
991        self.fu_header
992    }
993
994    /// donl returns the DONL of the packet.
995    pub fn donl(&self) -> Option<u16> {
996        self.donl
997    }
998
999    /// payload returns the Fragmentation Unit packet payload.
1000    pub fn payload(&self) -> Bytes {
1001        self.payload.clone()
1002    }
1003}
1004
1005///
1006/// PACI implementation
1007///
1008/// H265PACIPacket represents a single H265 PACI packet.
1009///
1010///  0                   1                   2                   3
1011/// 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
1012/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1013/// |    PayloadHdr (Type=50)       |A|   cType   | phssize |F0..2|Y|
1014/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1015/// |        payload Header Extension Structure (phes)              |
1016/// |=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=|
1017/// |                                                               |
1018/// |                  PACI payload: NAL unit                       |
1019/// |                   . . .                                       |
1020/// |                                                               |
1021/// |                               +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1022/// |                               :...OPTIONAL RTP padding        |
1023/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1024///
1025/// ## Specifications
1026///
1027/// * [RFC 7798 §4.4.4]
1028///
1029/// [RFC 7798 §4.4.4]: https://tools.ietf.org/html/rfc7798#section-4.4.4
1030#[derive(Default, Debug, Clone, PartialEq, Eq)]
1031pub struct H265PACIPacket {
1032    /// payload_header is the header of the H265 packet.
1033    payload_header: H265NALUHeader,
1034
1035    /// Field which holds value for `A`, `cType`, `phssize`, `F0`, `F1`, `F2` and `Y` fields.
1036    paci_header_fields: u16,
1037
1038    /// phes is a header extension, of byte length `phssize`
1039    phes: Bytes,
1040
1041    /// payload contains NAL units & optional padding
1042    payload: Bytes,
1043}
1044
1045impl H265PACIPacket {
1046    /// payload_header returns the NAL Unit Header.
1047    pub fn payload_header(&self) -> H265NALUHeader {
1048        self.payload_header
1049    }
1050
1051    /// a copies the F bit of the PACI payload NALU.
1052    pub fn a(&self) -> bool {
1053        const MASK: u16 = 0b10000000 << 8;
1054        (self.paci_header_fields & MASK) != 0
1055    }
1056
1057    /// ctype copies the Type field of the PACI payload NALU.
1058    pub fn ctype(&self) -> u8 {
1059        const MASK: u16 = 0b01111110 << 8;
1060        ((self.paci_header_fields & MASK) >> (8 + 1)) as u8
1061    }
1062
1063    /// phs_size indicates the size of the phes field.
1064    pub fn phs_size(&self) -> u8 {
1065        const MASK: u16 = (0b00000001 << 8) | 0b11110000;
1066        ((self.paci_header_fields & MASK) >> 4) as u8
1067    }
1068
1069    /// f0 indicates the presence of a Temporal Scalability support extension in the phes.
1070    pub fn f0(&self) -> bool {
1071        const MASK: u16 = 0b00001000;
1072        (self.paci_header_fields & MASK) != 0
1073    }
1074
1075    /// f1 must be zero, reserved for future extensions.
1076    pub fn f1(&self) -> bool {
1077        const MASK: u16 = 0b00000100;
1078        (self.paci_header_fields & MASK) != 0
1079    }
1080
1081    /// f2 must be zero, reserved for future extensions.
1082    pub fn f2(&self) -> bool {
1083        const MASK: u16 = 0b00000010;
1084        (self.paci_header_fields & MASK) != 0
1085    }
1086
1087    /// y must be zero, reserved for future extensions.
1088    pub fn y(&self) -> bool {
1089        const MASK: u16 = 0b00000001;
1090        (self.paci_header_fields & MASK) != 0
1091    }
1092
1093    /// phes contains header extensions. Its size is indicated by phssize.
1094    pub fn phes(&self) -> Bytes {
1095        self.phes.clone()
1096    }
1097
1098    /// payload is a single NALU or NALU-like struct, not including the first two octets (header).
1099    pub fn payload(&self) -> Bytes {
1100        self.payload.clone()
1101    }
1102
1103    /// tsci returns the Temporal Scalability Control Information extension, if present.
1104    pub fn tsci(&self) -> Option<H265TSCI> {
1105        if !self.f0() || self.phs_size() < 3 || self.phes.len() < 3 {
1106            return None;
1107        }
1108
1109        // TL0PICIDX, IrapPicID, then S, E and RES: the first three octets of the PHES, in the
1110        // high 24 bits of the value, which is where the accessors read them.
1111        Some(H265TSCI(
1112            ((self.phes[0] as u32) << 24)
1113                | ((self.phes[1] as u32) << 16)
1114                | ((self.phes[2] as u32) << 8),
1115        ))
1116    }
1117
1118    /// depacketize parses the passed byte slice and stores the result in the H265PACIPacket this method is called upon.
1119    fn depacketize(&mut self, payload: &Bytes) -> Result<()> {
1120        const TOTAL_HEADER_SIZE: usize = H265NALU_HEADER_SIZE + 2;
1121        if payload.len() <= TOTAL_HEADER_SIZE {
1122            return Err(Error::ErrShortPacket);
1123        }
1124
1125        let payload_header = H265NALUHeader::new(payload[0], payload[1]);
1126        if payload_header.f() {
1127            return Err(Error::ErrH265CorruptedPacket);
1128        }
1129        if !payload_header.is_paci_packet() {
1130            return Err(Error::ErrInvalidH265PacketType);
1131        }
1132
1133        let paci_header_fields = ((payload[2] as u16) << 8) | (payload[3] as u16);
1134        let mut payload = payload.slice(4..);
1135
1136        self.paci_header_fields = paci_header_fields;
1137        let header_extension_size = self.phs_size();
1138
1139        if payload.len() < header_extension_size as usize + 1 {
1140            self.paci_header_fields = 0;
1141            return Err(Error::ErrShortPacket);
1142        }
1143
1144        self.payload_header = payload_header;
1145
1146        if header_extension_size > 0 {
1147            self.phes = payload.slice(..header_extension_size as usize);
1148        }
1149
1150        payload = payload.slice(header_extension_size as usize..);
1151        self.payload = payload;
1152
1153        Ok(())
1154    }
1155}
1156
1157///
1158/// Temporal Scalability Control Information
1159///
1160/// H265TSCI is a Temporal Scalability Control Information header extension.
1161///
1162/// ## Specifications
1163///
1164/// * [RFC 7798 §4.5]
1165///
1166/// [RFC 7798 §4.5]: https://tools.ietf.org/html/rfc7798#section-4.5
1167#[derive(Default, Debug, Copy, Clone, PartialEq, Eq)]
1168pub struct H265TSCI(pub u32);
1169
1170impl H265TSCI {
1171    /// tl0picidx see RFC7798 for more details.
1172    pub fn tl0picidx(&self) -> u8 {
1173        const M1: u32 = 0xFFFF0000;
1174        const M2: u32 = 0xFF00;
1175        ((((self.0 & M1) >> 16) & M2) >> 8) as u8
1176    }
1177
1178    /// irap_pic_id see RFC7798 for more details.
1179    pub fn irap_pic_id(&self) -> u8 {
1180        const M1: u32 = 0xFFFF0000;
1181        const M2: u32 = 0x00FF;
1182        (((self.0 & M1) >> 16) & M2) as u8
1183    }
1184
1185    /// s see RFC7798 for more details.
1186    pub fn s(&self) -> bool {
1187        const M1: u32 = 0xFF00;
1188        const M2: u32 = 0b10000000;
1189        (((self.0 & M1) >> 8) & M2) != 0
1190    }
1191
1192    /// e see RFC7798 for more details.
1193    pub fn e(&self) -> bool {
1194        const M1: u32 = 0xFF00;
1195        const M2: u32 = 0b01000000;
1196        (((self.0 & M1) >> 8) & M2) != 0
1197    }
1198
1199    /// res see RFC7798 for more details.
1200    pub fn res(&self) -> u8 {
1201        const M1: u32 = 0xFF00;
1202        const M2: u32 = 0b00111111;
1203        (((self.0 & M1) >> 8) & M2) as u8
1204    }
1205}
1206
1207///
1208/// H265 Payload Enum
1209///
1210#[derive(Debug, Clone, PartialEq, Eq)]
1211#[non_exhaustive]
1212pub enum H265Payload {
1213    /// One NAL unit carried whole in a single packet.
1214    H265SingleNALUnitPacket(H265SingleNALUnitPacket),
1215    /// One fragment of a NAL unit too large for the MTU.
1216    H265FragmentationUnitPacket(H265FragmentationUnitPacket),
1217    /// Several small NAL units aggregated into one packet.
1218    H265AggregationPacket(H265AggregationPacket),
1219    /// A PACI packet, which carries payload content information ahead of the NAL unit.
1220    H265PACIPacket(H265PACIPacket),
1221}
1222
1223impl Default for H265Payload {
1224    fn default() -> Self {
1225        H265Payload::H265SingleNALUnitPacket(H265SingleNALUnitPacket::default())
1226    }
1227}
1228
1229/// One NAL unit taken out of an RTP payload.
1230#[derive(Debug, Clone, PartialEq, Eq)]
1231pub struct H265NalUnit {
1232    /// The NAL unit, its two-byte header included, without a start code or a length prefix.
1233    pub data: Bytes,
1234    /// Its decoding order number, on a stream that carries them (`sprop-max-don-diff` greater
1235    /// than 0): the DONL of its packet, or the previous unit's DON plus DOND plus one inside an
1236    /// aggregation packet (RFC 7798 sections 4.4.1 to 4.4.3).
1237    pub don: Option<u16>,
1238}
1239
1240#[derive(Debug, Clone, PartialEq, Eq)]
1241struct BufferedH265NalUnit {
1242    unit: H265NalUnit,
1243    /// AbsDon of RFC 7798 section 4.6: the DON unwrapped along the reception order.
1244    abs_don: i64,
1245}
1246
1247/// The de-packetization buffer of RFC 7798 section 6, for a stream whose `sprop-max-don-diff`
1248/// is greater than 0: NAL units go in in reception order and come out in decoding order, by
1249/// AbsDon (section 4.6).
1250///
1251/// A NAL unit leaves, the smallest AbsDon first, whenever the AbsDon values in the buffer span
1252/// `sprop-max-don-diff` or more (condition A) or the buffer holds more than
1253/// `sprop-depack-buf-nalus` NAL units (condition B).
1254#[derive(Debug, Clone, PartialEq, Eq)]
1255pub struct H265DepacketizationBuffer {
1256    max_don_diff: i64,
1257    depack_buf_nalus: usize,
1258    units: Vec<BufferedH265NalUnit>,
1259    /// The DON and AbsDon of the NAL unit received last.
1260    last_received: Option<(u16, i64)>,
1261    bytes: usize,
1262}
1263
1264impl H265DepacketizationBuffer {
1265    /// A buffer for a stream with these `sprop-max-don-diff` and `sprop-depack-buf-nalus`
1266    /// media type parameters (RFC 7798 section 7.1; both are 0 to 32767).
1267    pub fn new(sprop_max_don_diff: u16, sprop_depack_buf_nalus: u16) -> Self {
1268        H265DepacketizationBuffer {
1269            max_don_diff: i64::from(sprop_max_don_diff),
1270            depack_buf_nalus: usize::from(sprop_depack_buf_nalus),
1271            units: Vec::new(),
1272            last_received: None,
1273            bytes: 0,
1274        }
1275    }
1276
1277    /// NAL units in the buffer.
1278    pub fn len(&self) -> usize {
1279        self.units.len()
1280    }
1281
1282    /// Whether the buffer holds no NAL unit.
1283    pub fn is_empty(&self) -> bool {
1284        self.units.is_empty()
1285    }
1286
1287    fn due(&self) -> bool {
1288        let mut abs_dons = self.units.iter().map(|buffered| buffered.abs_don);
1289        let Some(first) = abs_dons.next() else {
1290            return false;
1291        };
1292        let (smallest, greatest) = abs_dons
1293            .fold((first, first), |(smallest, greatest), abs_don| {
1294                (smallest.min(abs_don), greatest.max(abs_don))
1295            });
1296        // Condition A, condition B, and the bound.
1297        greatest - smallest >= self.max_don_diff
1298            || self.units.len() > self.depack_buf_nalus
1299            || self.units.len() > MAX_DEPACKETIZATION_NAL_UNITS
1300            || self.bytes > MAX_DEPACKETIZATION_BYTES
1301    }
1302
1303    /// Stores a NAL unit and returns the NAL units that are now due, in decoding order. A NAL
1304    /// unit without a DON is returned as it is.
1305    pub fn push(&mut self, unit: H265NalUnit) -> Vec<H265NalUnit> {
1306        let Some(don) = unit.don else {
1307            return vec![unit];
1308        };
1309        let abs_don = match self.last_received {
1310            Some((last_don, last_abs)) => last_abs + i64::from(don_diff(last_don, don)),
1311            None => i64::from(don),
1312        };
1313        self.last_received = Some((don, abs_don));
1314        self.bytes += unit.data.len();
1315        self.units.push(BufferedH265NalUnit { unit, abs_don });
1316
1317        let mut out = vec![];
1318        while self.due() {
1319            // The NAL unit with the smallest AbsDon; the earliest received among equals.
1320            let index = (0..self.units.len())
1321                .min_by_key(|&i| self.units[i].abs_don)
1322                .unwrap_or(0);
1323            let buffered = self.units.remove(index);
1324            self.bytes -= buffered.unit.data.len();
1325            out.push(buffered.unit);
1326        }
1327        out
1328    }
1329
1330    /// Empties the buffer, in order of increasing AbsDon: no more NAL units are coming.
1331    pub fn flush(&mut self) -> Vec<H265NalUnit> {
1332        let mut buffered = std::mem::take(&mut self.units);
1333        self.bytes = 0;
1334        buffered.sort_by_key(|buffered| buffered.abs_don);
1335        buffered.into_iter().map(|buffered| buffered.unit).collect()
1336    }
1337}
1338
1339/// One RTP stream of an [`H265MultiStreamDepacketizer`].
1340#[derive(Debug, Clone)]
1341struct H265ReceivedStream {
1342    id: u32,
1343    max_don_diff: u16,
1344    parser: H265Packet,
1345    /// The sequence number of the last packet taken.
1346    last_sequence_number: Option<u16>,
1347    /// The DON and AbsDon of this stream's NAL unit received last (RFC 7798 section 4.6:
1348    /// AbsDon is derived along each stream's transmission order).
1349    last_don: Option<(u16, i64)>,
1350    /// The greatest NTP timestamp seen on the stream.
1351    latest_ntp: Option<u64>,
1352}
1353
1354/// A NAL unit waiting in an [`H265MultiStreamDepacketizer`].
1355#[derive(Debug, Clone)]
1356struct PendingH265NalUnit {
1357    unit: H265NalUnit,
1358    /// The position of its stream in the dependency order.
1359    rank: usize,
1360    /// AbsDon when decoding order numbers are in use, else 0.
1361    abs_don: i64,
1362    /// The NTP timestamp when no decoding order numbers are in use, else 0.
1363    ntp: u64,
1364    /// Reception order.
1365    arrival: u64,
1366}
1367
1368/// The receiver of an HEVC bitstream carried in several RTP streams: MRST (several streams on
1369/// one transport) and MRMT (several streams on several transports), RFC 7798 section 4.3:
1370/// "Receivers MUST support all of SRST, MRST, and MRMT". It holds the RTP streams of one
1371/// bitstream, in dependency order, and passes their NAL units on in decoding order as RFC 7798
1372/// section 6 describes:
1373///
1374/// - When `sprop-max-don-diff` is greater than 0 for any of the streams, the NAL units of all
1375///   of them are stored in one de-packetization buffer with their AbsDon (section 4.6, derived
1376///   along each stream) and leave, the smallest AbsDon first, while the AbsDon values span the
1377///   highest stream's `sprop-max-don-diff` or more (condition A) or the buffer holds more than
1378///   `sprop-depack-buf-nalus` NAL units (condition B). Among equal AbsDon values a stream lower
1379///   in the dependency order goes first.
1380/// - Otherwise the NAL units are passed on in the order of their NTP timestamps; of the same
1381///   timestamp, a dependee stream's before a dependent's, and one stream's in transmission
1382///   order. The caller gives each packet's NTP timestamp (its RTP timestamp mapped through the
1383///   stream's sender reports). A NAL unit leaves once no stream can still deliver one that goes
1384///   before it: every stream it depends on has shown a later timestamp, and every dependent
1385///   stream received so far the same timestamp or a later one.
1386///
1387/// Duplicated and outdated packets (a sequence number not after the stream's last) are removed
1388/// (section 6). Give each stream's packets in sequence number order, after the jitter buffer:
1389/// an MRMT receiver feeds the packets of each transport's streams into the same instance. The
1390/// grouping of the streams (which streams make one bitstream and their dependency order) is
1391/// signalled with RFC 5583 `a=depend`, which the application reads from the description.
1392#[derive(Debug, Clone)]
1393pub struct H265MultiStreamDepacketizer {
1394    depack_buf_nalus: usize,
1395    streams: Vec<H265ReceivedStream>,
1396    pending: Vec<PendingH265NalUnit>,
1397    bytes: usize,
1398    arrivals: u64,
1399}
1400
1401impl H265MultiStreamDepacketizer {
1402    /// A receiver whose bitstream has this `sprop-depack-buf-nalus` (RFC 7798 section 7.1; 0
1403    /// when the description gives none).
1404    pub fn new(sprop_depack_buf_nalus: u16) -> Self {
1405        H265MultiStreamDepacketizer {
1406            depack_buf_nalus: usize::from(sprop_depack_buf_nalus),
1407            streams: Vec::new(),
1408            pending: Vec::new(),
1409            bytes: 0,
1410            arrivals: 0,
1411        }
1412    }
1413
1414    /// Adds the RTP stream `id` (an SSRC, or any number the caller tells the streams apart by)
1415    /// with its `sprop-max-don-diff`. Streams are added in dependency order: a stream depends
1416    /// only on streams added before it. Adding a stream already held changes nothing.
1417    pub fn add_stream(&mut self, id: u32, sprop_max_don_diff: u16) {
1418        if self.streams.iter().any(|stream| stream.id == id) {
1419            return;
1420        }
1421        self.streams.push(H265ReceivedStream {
1422            id,
1423            max_don_diff: sprop_max_don_diff,
1424            parser: H265Packet::default(),
1425            last_sequence_number: None,
1426            last_don: None,
1427            latest_ntp: None,
1428        });
1429        // DONL and DOND are present on every stream as soon as one of them carries DONs.
1430        let donl = self.uses_don();
1431        for stream in &mut self.streams {
1432            stream.parser.with_donl(donl);
1433        }
1434    }
1435
1436    /// NAL units waiting.
1437    pub fn len(&self) -> usize {
1438        self.pending.len()
1439    }
1440
1441    /// Whether no NAL unit is waiting.
1442    pub fn is_empty(&self) -> bool {
1443        self.pending.is_empty()
1444    }
1445
1446    /// Whether decoding order numbers are in use: `sprop-max-don-diff` greater than 0 for any
1447    /// of the streams (RFC 7798 section 4.6).
1448    fn uses_don(&self) -> bool {
1449        self.streams.iter().any(|stream| stream.max_don_diff > 0)
1450    }
1451
1452    /// Takes one RTP packet of stream `stream`: its sequence number, its NTP timestamp and its
1453    /// payload. Returns the NAL units now due, in decoding order. A packet of a stream not
1454    /// added, a duplicate and an outdated packet give nothing.
1455    ///
1456    /// # Errors
1457    ///
1458    /// As [`H265Packet::nal_units`].
1459    pub fn push(
1460        &mut self,
1461        stream: u32,
1462        sequence_number: u16,
1463        ntp: u64,
1464        payload: &Bytes,
1465    ) -> Result<Vec<H265NalUnit>> {
1466        let uses_don = self.uses_don();
1467        let Some(rank) = self.streams.iter().position(|s| s.id == stream) else {
1468            return Ok(vec![]);
1469        };
1470        let received = &mut self.streams[rank];
1471        if let Some(last) = received.last_sequence_number {
1472            let ahead = sequence_number.wrapping_sub(last);
1473            if ahead == 0 || ahead >= 0x8000 {
1474                return Ok(vec![]);
1475            }
1476        }
1477        received.last_sequence_number = Some(sequence_number);
1478        received.parser.note_sequence_number(sequence_number);
1479        let units = received.parser.nal_units(payload)?;
1480        received.latest_ntp = Some(received.latest_ntp.map_or(ntp, |latest| latest.max(ntp)));
1481        for unit in units {
1482            let (abs_don, ntp) = if uses_don {
1483                // DONL is present on every stream when any of them uses decoding order
1484                // numbers (RFC 7798 section 4.4.1).
1485                let Some(don) = unit.don else {
1486                    continue;
1487                };
1488                let abs_don = match received.last_don {
1489                    Some((last_don, last_abs)) => last_abs + i64::from(don_diff(last_don, don)),
1490                    None => i64::from(don),
1491                };
1492                received.last_don = Some((don, abs_don));
1493                (abs_don, 0)
1494            } else {
1495                (0, ntp)
1496            };
1497            self.bytes += unit.data.len();
1498            self.arrivals += 1;
1499            self.pending.push(PendingH265NalUnit {
1500                unit,
1501                rank,
1502                abs_don,
1503                ntp,
1504                arrival: self.arrivals,
1505            });
1506        }
1507        Ok(self.release())
1508    }
1509
1510    /// The index of the waiting NAL unit that goes first in decoding order.
1511    fn first(&self) -> Option<usize> {
1512        (0..self.pending.len()).min_by_key(|&i| {
1513            let unit = &self.pending[i];
1514            (unit.abs_don, unit.ntp, unit.rank, unit.arrival)
1515        })
1516    }
1517
1518    fn over_bound(&self) -> bool {
1519        self.pending.len() > MAX_DEPACKETIZATION_NAL_UNITS || self.bytes > MAX_DEPACKETIZATION_BYTES
1520    }
1521
1522    /// Whether the waiting NAL unit `index` may leave.
1523    fn due(&self, index: usize) -> bool {
1524        if self.over_bound() {
1525            return true;
1526        }
1527        if self.uses_don() {
1528            let (smallest, greatest) = self.pending.iter().fold((i64::MAX, i64::MIN), |acc, u| {
1529                (acc.0.min(u.abs_don), acc.1.max(u.abs_don))
1530            });
1531            // The highest stream in the dependency order that uses decoding order numbers.
1532            let max_don_diff = self
1533                .streams
1534                .iter()
1535                .rev()
1536                .map(|stream| stream.max_don_diff)
1537                .find(|diff| *diff > 0)
1538                .unwrap_or(0);
1539            // Condition A or condition B.
1540            greatest - smallest >= i64::from(max_don_diff)
1541                || self.pending.len() > self.depack_buf_nalus
1542        } else {
1543            // No stream can still deliver a NAL unit that goes before this one: a dependee
1544            // (lower in the dependency order) has shown a later timestamp, and a dependent
1545            // received so far has shown this one or a later one. A dependent's NAL unit waits
1546            // for its dependees to be received at all: it cannot be decoded without them.
1547            let unit = &self.pending[index];
1548            self.streams
1549                .iter()
1550                .enumerate()
1551                .all(|(rank, stream)| match rank.cmp(&unit.rank) {
1552                    std::cmp::Ordering::Equal => true,
1553                    std::cmp::Ordering::Less => {
1554                        stream.latest_ntp.is_some_and(|latest| latest > unit.ntp)
1555                    }
1556                    std::cmp::Ordering::Greater => {
1557                        stream.latest_ntp.is_none_or(|latest| latest >= unit.ntp)
1558                    }
1559                })
1560        }
1561    }
1562
1563    fn release(&mut self) -> Vec<H265NalUnit> {
1564        let mut out = vec![];
1565        while let Some(index) = self.first() {
1566            if !self.due(index) {
1567                break;
1568            }
1569            let pending = self.pending.remove(index);
1570            self.bytes -= pending.unit.data.len();
1571            out.push(pending.unit);
1572        }
1573        out
1574    }
1575
1576    /// Every NAL unit still waiting, in decoding order: no more packets are coming.
1577    pub fn flush(&mut self) -> Vec<H265NalUnit> {
1578        let mut pending = std::mem::take(&mut self.pending);
1579        self.bytes = 0;
1580        pending.sort_by_key(|unit| (unit.abs_don, unit.ntp, unit.rank, unit.arrival));
1581        pending.into_iter().map(|pending| pending.unit).collect()
1582    }
1583}
1584
1585///
1586/// Packet implementation
1587///
1588/// H265Packet represents a H265 packet, stored in the payload of an RTP packet.
1589///
1590/// As a [`Depacketizer`] it turns RTP payloads into NAL units, in an Annex B byte stream (or
1591/// length-prefixed, see [`with_length_prefix`](H265Packet::with_length_prefix)): a single NAL
1592/// unit packet's NAL unit, each NAL unit of an aggregation packet, a NAL unit reassembled from
1593/// its fragmentation units, and whichever of those a PACI packet carries. Nothing of type 48
1594/// to 63 is ever passed on (RFC 7798 section 6).
1595#[derive(Default, Debug, Clone, PartialEq, Eq)]
1596pub struct H265Packet {
1597    payload: H265Payload,
1598    might_need_donl: bool,
1599    length_prefixed: bool,
1600    /// The NAL unit being reassembled from fragmentation units: its header, then the data.
1601    fu_buffer: Option<BytesMut>,
1602    /// Its decoding order number, from the first fragment's DONL.
1603    fu_don: Option<u16>,
1604    /// The sequence number of the last packet given with one.
1605    last_sequence_number: Option<u16>,
1606    depacketization: Option<H265DepacketizationBuffer>,
1607}
1608
1609impl H265Packet {
1610    /// with_donl can be called to specify whether or not DONL might be parsed.
1611    /// DONL may need to be parsed if `sprop-max-don-diff` is greater than 0 on the RTP stream.
1612    pub fn with_donl(&mut self, value: bool) {
1613        self.might_need_donl = value;
1614    }
1615
1616    /// Emits each NAL unit with a four-byte big-endian length before it (the `hvcC` sample
1617    /// format) in place of an Annex B start code.
1618    pub fn with_length_prefix(&mut self, value: bool) {
1619        self.length_prefixed = value;
1620    }
1621
1622    /// Receives a stream whose `sprop-max-don-diff` is greater than 0 in decoding order: DONL
1623    /// and DOND are parsed, and NAL units go through `buffer` before
1624    /// [`depacketize`](Depacketizer::depacketize) returns them (RFC 7798 section 6).
1625    pub fn with_depacketization_buffer(&mut self, buffer: H265DepacketizationBuffer) {
1626        self.might_need_donl = true;
1627        self.depacketization = Some(buffer);
1628    }
1629
1630    /// The NAL units still in the de-packetization buffer, in decoding order and in the output
1631    /// format of [`depacketize`](Depacketizer::depacketize): for the end of the stream.
1632    pub fn flush_depacketization_buffer(&mut self) -> Bytes {
1633        let units = self
1634            .depacketization
1635            .as_mut()
1636            .map(H265DepacketizationBuffer::flush)
1637            .unwrap_or_default();
1638        self.format(&units)
1639    }
1640
1641    /// payload returns the populated payload.
1642    /// Must be casted to one of:
1643    /// - H265SingleNALUnitPacket
1644    /// - H265FragmentationUnitPacket
1645    /// - H265AggregationPacket
1646    /// - H265PACIPacket
1647    pub fn payload(&self) -> &H265Payload {
1648        &self.payload
1649    }
1650
1651    /// As [`depacketize`](Depacketizer::depacketize), given the packet's RTP sequence number:
1652    /// when a packet is missing before this one, the fragments collected so far are discarded
1653    /// with the rest of their NAL unit, in place of a NAL unit with a hole in it (RFC 7798
1654    /// section 4.4.3). Give the packets in sequence number order.
1655    ///
1656    /// # Errors
1657    ///
1658    /// As [`depacketize`](Depacketizer::depacketize).
1659    pub fn depacketize_with_sequence_number(
1660        &mut self,
1661        sequence_number: u16,
1662        payload: &Bytes,
1663    ) -> Result<Bytes> {
1664        self.note_sequence_number(sequence_number);
1665        self.depacketize(payload)
1666    }
1667
1668    /// Takes note of the next packet's sequence number: after a gap the fragments collected so
1669    /// far are discarded.
1670    fn note_sequence_number(&mut self, sequence_number: u16) {
1671        // A repeated number is a duplicate, not a gap.
1672        if let Some(last) = self.last_sequence_number
1673            && sequence_number != last.wrapping_add(1)
1674            && sequence_number != last
1675        {
1676            self.fu_buffer = None;
1677            self.fu_don = None;
1678        }
1679        self.last_sequence_number = Some(sequence_number);
1680    }
1681
1682    /// Whether a NAL unit may be passed to a decoder: a whole header and a type below 48.
1683    fn is_nal_unit(data: &[u8]) -> bool {
1684        data.len() >= H265NALU_HEADER_SIZE
1685            && H265NALUHeader::new(data[0], data[1]).nalu_type() < H265NALU_AGGREGATION_PACKET_TYPE
1686    }
1687
1688    /// The NAL units a payload completes, with their decoding order numbers when the stream
1689    /// carries them: one for a single NAL unit packet, two or more for an aggregation packet,
1690    /// none or one for a fragmentation unit, and those of the packet a PACI carries. The
1691    /// de-packetization buffer is not involved. [`payload`](H265Packet::payload) is the
1692    /// parsed packet afterwards.
1693    ///
1694    /// # Errors
1695    ///
1696    /// Fails for a payload cut short, a packet with the F bit set, and a reassembly over
1697    /// [`MAX_H265_FU_NALU_SIZE`].
1698    pub fn nal_units(&mut self, payload: &Bytes) -> Result<Vec<H265NalUnit>> {
1699        if payload.len() < H265NALU_HEADER_SIZE {
1700            return Err(Error::ErrShortPacket);
1701        }
1702
1703        let payload_header = H265NALUHeader::new(payload[0], payload[1]);
1704        if payload_header.f() {
1705            return Err(Error::ErrH265CorruptedPacket);
1706        }
1707
1708        if payload_header.is_paci_packet() {
1709            let mut decoded = H265PACIPacket::default();
1710            decoded.depacketize(payload)?;
1711            if decoded.ctype() == H265NALU_PACI_PACKET_TYPE {
1712                // A PACI carries a single NAL unit, an FU or an AP, not a PACI: there is
1713                // nothing in it to pass on.
1714                self.payload = H265Payload::H265PACIPacket(decoded);
1715                return Ok(vec![]);
1716            }
1717            // The packet a PACI carries: its payload header is the PACI's with F and Type
1718            // replaced by the A and cType fields, and its body is the PACI payload (RFC 7798
1719            // section 4.4.4).
1720            let mut header = (decoded.ctype() as u16) << 9;
1721            header |= (payload_header.layer_id() as u16) << 3;
1722            header |= payload_header.tid() as u16;
1723            if decoded.a() {
1724                header |= 1 << 15;
1725            }
1726            let mut carried = BytesMut::with_capacity(2 + decoded.payload.len());
1727            carried.put_u16(header);
1728            carried.extend_from_slice(&decoded.payload);
1729            let units = self.nal_units(&carried.freeze());
1730            self.payload = H265Payload::H265PACIPacket(decoded);
1731            units
1732        } else if payload_header.is_fragmentation_unit() {
1733            let mut decoded = H265FragmentationUnitPacket::default();
1734            decoded.with_donl(self.might_need_donl);
1735
1736            if let Err(err) = decoded.depacketize(payload) {
1737                self.fu_buffer = None;
1738                self.fu_don = None;
1739                return Err(err);
1740            }
1741
1742            let fu_header = decoded.fu_header();
1743            if fu_header.s() {
1744                if fu_header.fu_type() < H265NALU_AGGREGATION_PACKET_TYPE {
1745                    // The NAL unit header: the payload header with the FU's type.
1746                    let mut header = (fu_header.fu_type() as u16) << 9;
1747                    header |= (payload_header.layer_id() as u16) << 3;
1748                    header |= payload_header.tid() as u16;
1749                    let mut buffer = BytesMut::new();
1750                    buffer.put_u16(header);
1751                    self.fu_buffer = Some(buffer);
1752                    self.fu_don = decoded.donl();
1753                } else {
1754                    // A fragmented aggregation packet, fragment or PACI: not a NAL unit.
1755                    self.fu_buffer = None;
1756                    self.fu_don = None;
1757                }
1758            }
1759            let mut units = vec![];
1760            if let Some(buffer) = &mut self.fu_buffer {
1761                if buffer.len() + decoded.payload.len() > MAX_H265_FU_NALU_SIZE {
1762                    // Bounded: a peer that never sends the end fragment must not grow this
1763                    // without limit. Drop the partial NAL unit.
1764                    self.fu_buffer = None;
1765                    self.fu_don = None;
1766                    self.payload = H265Payload::H265FragmentationUnitPacket(decoded);
1767                    return Err(Error::ErrPacketTooBig);
1768                }
1769                buffer.extend_from_slice(&decoded.payload);
1770                if fu_header.e()
1771                    && let Some(buffer) = self.fu_buffer.take()
1772                {
1773                    units.push(H265NalUnit {
1774                        data: buffer.freeze(),
1775                        don: self.fu_don.take(),
1776                    });
1777                }
1778            }
1779            // A fragment whose start was lost has nothing to join: it is dropped.
1780            self.payload = H265Payload::H265FragmentationUnitPacket(decoded);
1781            Ok(units)
1782        } else if payload_header.is_aggregation_packet() {
1783            let mut decoded = H265AggregationPacket::default();
1784            decoded.with_donl(self.might_need_donl);
1785
1786            decoded.depacketize(payload)?;
1787
1788            let mut units = vec![];
1789            let mut don = None;
1790            if let Some(first) = decoded.first_unit() {
1791                don = first.donl();
1792                if Self::is_nal_unit(&first.nal_unit) {
1793                    units.push(H265NalUnit {
1794                        data: first.nal_unit(),
1795                        don,
1796                    });
1797                }
1798            }
1799            for unit in decoded.other_units() {
1800                // DON = the previous unit's DON + DOND + 1, modulo 65536.
1801                don = don
1802                    .zip(unit.dond())
1803                    .map(|(don, dond)| don.wrapping_add(u16::from(dond)).wrapping_add(1));
1804                // An aggregated aggregation packet, fragment or PACI is not a NAL unit.
1805                if Self::is_nal_unit(&unit.nal_unit) {
1806                    units.push(H265NalUnit {
1807                        data: unit.nal_unit(),
1808                        don,
1809                    });
1810                }
1811            }
1812            self.payload = H265Payload::H265AggregationPacket(decoded);
1813            Ok(units)
1814        } else {
1815            let mut decoded = H265SingleNALUnitPacket::default();
1816            decoded.with_donl(self.might_need_donl);
1817
1818            decoded.depacketize(payload)?;
1819
1820            let mut units = vec![];
1821            // Types 51 to 63 are reserved: not passed on.
1822            if payload_header.nalu_type() < H265NALU_AGGREGATION_PACKET_TYPE {
1823                let mut data = BytesMut::with_capacity(2 + decoded.payload.len());
1824                data.put_u16(payload_header.0);
1825                data.extend_from_slice(&decoded.payload);
1826                units.push(H265NalUnit {
1827                    data: data.freeze(),
1828                    don: decoded.donl(),
1829                });
1830            }
1831            self.payload = H265Payload::H265SingleNALUnitPacket(decoded);
1832            Ok(units)
1833        }
1834    }
1835
1836    /// NAL units as an Annex B byte stream, or length-prefixed.
1837    fn format(&self, units: &[H265NalUnit]) -> Bytes {
1838        let mut out = BytesMut::with_capacity(units.iter().map(|unit| 4 + unit.data.len()).sum());
1839        for unit in units {
1840            if self.length_prefixed {
1841                out.put_u32(unit.data.len() as u32);
1842            } else {
1843                out.put(&*ANNEXB_NALUSTART_CODE);
1844            }
1845            out.put(&*unit.data);
1846        }
1847        out.freeze()
1848    }
1849}
1850
1851impl Depacketizer for H265Packet {
1852    /// Parses one RTP payload and returns the NAL units it completes, each behind an Annex B
1853    /// start code (or a length prefix): empty for a fragment that does not end its NAL unit.
1854    fn depacketize(&mut self, payload: &Bytes) -> Result<Bytes> {
1855        let mut units = self.nal_units(payload)?;
1856        if let Some(buffer) = &mut self.depacketization {
1857            units = units
1858                .into_iter()
1859                .flat_map(|unit| buffer.push(unit))
1860                .collect();
1861        }
1862        Ok(self.format(&units))
1863    }
1864
1865    /// is_partition_head checks if this is the head of a packetized nalu stream.
1866    ///
1867    /// Every payload begins a NAL unit except a fragmentation unit whose start bit is clear
1868    /// (RFC 7798 4.4.3: the FU header's S bit marks the first fragment). A fragmentation unit too
1869    /// short to carry its FU header cannot begin anything.
1870    fn is_partition_head(&self, payload: &Bytes) -> bool {
1871        if payload.len() < H265NALU_HEADER_SIZE {
1872            return false;
1873        }
1874        let nalu_type = (payload[0] >> 1) & 0x3F;
1875        if nalu_type != H265NALU_FRAGMENTATION_UNIT_TYPE {
1876            return true;
1877        }
1878        payload
1879            .get(H265NALU_HEADER_SIZE)
1880            .is_some_and(|fu_header| fu_header & 0x80 != 0)
1881    }
1882
1883    fn is_partition_tail(&self, marker: bool, _payload: &Bytes) -> bool {
1884        marker
1885    }
1886}