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