Skip to main content

rtci_rtp/codec/h264/
mod.rs

1//! H.264 RTP payload format ([RFC 6184]).
2//!
3//! All three packetization modes are here:
4//!
5//! * mode 0, single NAL unit (section 6.2): every NAL unit in a packet of its own;
6//! * mode 1, non-interleaved (section 6.3), the default and what WebRTC uses: single NAL unit
7//!   packets, STAP-A aggregates and FU-A fragments, in decoding order;
8//! * mode 2, interleaved (section 6.4): STAP-B, MTAP16, MTAP24, FU-B and FU-A, every NAL unit
9//!   with a decoding order number (DON), and `H264DeinterleavingBuffer` to put received NAL
10//!   units back in decoding order (section 7.2.2).
11//!
12//! `H264Payloader` sends and `H264Packet` receives. The `*_NALU_TYPE` constants name the
13//! types, and the `*_BITMASK` constants describe how the NAL header and FU header pack their
14//! fields.
15//!
16//! [RFC 6184]: https://datatracker.ietf.org/doc/html/rfc6184
17#[cfg(test)]
18mod h264_test;
19#[cfg(test)]
20mod interleaved_test;
21#[cfg(test)]
22mod packetization_mode_test;
23#[cfg(test)]
24mod rfc6184_test;
25
26use crate::packetizer::{Depacketizer, Payloader};
27use shared::error::{Error, Result};
28
29use bytes::{BufMut, Bytes, BytesMut};
30use std::time::{Duration, Instant};
31
32/// NAL type 24: STAP-A, which aggregates several small NAL units into one payload.
33pub const STAPA_NALU_TYPE: u8 = 24;
34/// NAL type 25: STAP-B, a STAP-A with a decoding order number (interleaved mode).
35pub const STAPB_NALU_TYPE: u8 = 25;
36/// NAL type 26: MTAP16, an aggregate of NAL units of several access units, with 16-bit
37/// timestamp offsets (interleaved mode).
38pub const MTAP16_NALU_TYPE: u8 = 26;
39/// NAL type 27: MTAP24, MTAP16 with 24-bit timestamp offsets.
40pub const MTAP24_NALU_TYPE: u8 = 27;
41/// NAL type 28: FU-A, which fragments one NAL unit across several payloads.
42pub const FUA_NALU_TYPE: u8 = 28;
43/// NAL type 29: FU-B, the first fragment of a NAL unit in interleaved mode: an FU-A with a
44/// decoding order number.
45pub const FUB_NALU_TYPE: u8 = 29;
46/// NAL type 7: sequence parameter set.
47pub const SPS_NALU_TYPE: u8 = 7;
48/// NAL type 8: picture parameter set.
49pub const PPS_NALU_TYPE: u8 = 8;
50/// NAL type 9: access unit delimiter.
51pub const AUD_NALU_TYPE: u8 = 9;
52/// NAL type 12: filler data, which is dropped rather than sent.
53pub const FILLER_NALU_TYPE: u8 = 12;
54
55/// Bytes of FU-A header prefixed to each fragment.
56pub const FUA_HEADER_SIZE: usize = 2;
57/// Bytes of FU-B header prefixed to a first fragment: FU indicator, FU header and DON.
58pub const FUB_HEADER_SIZE: usize = 4;
59
60/// Largest NAL unit reassembled from FU-A fragments. Far above any real slice (a 4K intra frame
61/// is a few hundred KiB); a reassembly that would grow past it is dropped.
62pub const MAX_FUA_NALU_SIZE: usize = 4 * 1024 * 1024;
63/// Bytes of STAP-A header prefixed to an aggregate.
64pub const STAPA_HEADER_SIZE: usize = 1;
65/// Bytes of STAP-B header prefixed to an aggregate: the type octet and the DON.
66pub const STAPB_HEADER_SIZE: usize = 3;
67/// Bytes of MTAP header prefixed to an aggregate: the type octet and the DON base.
68pub const MTAP_HEADER_SIZE: usize = 3;
69/// Bytes of length prefix before each NAL unit inside a STAP-A.
70pub const STAPA_NALU_LENGTH_SIZE: usize = 2;
71
72/// Mask selecting the NAL type from a NAL header byte.
73pub const NALU_TYPE_BITMASK: u8 = 0x1F;
74/// Mask selecting `nal_ref_idc` from a NAL header byte.
75pub const NALU_REF_IDC_BITMASK: u8 = 0x60;
76/// Mask selecting `forbidden_zero_bit` from a NAL header byte.
77pub const NALU_FORBIDDEN_BITMASK: u8 = 0x80;
78/// FU header start bit: this fragment begins a NAL unit.
79pub const FU_START_BITMASK: u8 = 0x80;
80/// FU header end bit: this fragment completes a NAL unit.
81pub const FU_END_BITMASK: u8 = 0x40;
82
83/// The STAP-A header byte for aggregated NAL units whose `nal_ref_idc` is 3 (parameter sets as
84/// encoders write them). The payloader computes the header from the units it aggregates (RFC
85/// 6184 section 5.7: F is the OR of their F bits, NRI the maximum of their NRIs); this constant
86/// is that value for the common case.
87pub const OUTPUT_STAP_AHEADER: u8 = 0x78;
88
89/// The Annex B start code (`00 00 00 01`) that delimits NAL units in a byte stream.
90pub static ANNEXB_NALUSTART_CODE: Bytes = Bytes::from_static(&[0x00, 0x00, 0x00, 0x01]);
91
92/// Parameter sets given in calls of their own are held for the access unit that follows, up to
93/// this many of them.
94const MAX_HELD_PARAMETER_SETS: usize = 64;
95/// And up to this many bytes.
96const MAX_HELD_PARAMETER_SET_BYTES: usize = 1024 * 1024;
97
98/// The NAL units of an Annex B byte stream, without their start codes (three or four bytes,
99/// mixed freely). A buffer with no start code is one NAL unit.
100pub(crate) fn annex_b_nal_units(payload: &Bytes) -> Vec<Bytes> {
101    /// The next start code at or after `start`: its offset, zeros included, and its length.
102    fn next_start_code(data: &[u8], start: usize) -> Option<(usize, usize)> {
103        let mut zero_count = 0;
104        for (i, &b) in data[start..].iter().enumerate() {
105            if b == 0 {
106                zero_count += 1;
107                continue;
108            } else if b == 1 && zero_count >= 2 {
109                return Some((start + i - zero_count, zero_count + 1));
110            }
111            zero_count = 0
112        }
113        None
114    }
115
116    let mut nalus = vec![];
117    let Some((mut code_start, mut code_len)) = next_start_code(payload, 0) else {
118        nalus.push(payload.clone());
119        return nalus;
120    };
121    loop {
122        let nalu_start = code_start + code_len;
123        match next_start_code(payload, nalu_start) {
124            Some((next_start, next_len)) => {
125                nalus.push(payload.slice(nalu_start..next_start));
126                code_start = next_start;
127                code_len = next_len;
128            }
129            None => {
130                nalus.push(payload.slice(nalu_start..));
131                return nalus;
132            }
133        }
134    }
135}
136
137/// Whether a NAL unit type is one a packet may carry as a NAL unit: 1 to 23. Type 0 and types
138/// 30 and 31 are reserved, and 24 to 29 are this payload format's own packet types (RFC 6184
139/// section 5.4, Table 3; section 5.7: aggregates are not nested; section 5.8: nor are FUs).
140fn is_nal_unit_type(nalu_type: u8) -> bool {
141    (1..=23).contains(&nalu_type)
142}
143
144/// Whether a NAL unit type is a coded slice or slice data partition (VCL): 1 to 5.
145fn is_vcl_type(nalu_type: u8) -> bool {
146    (1..=5).contains(&nalu_type)
147}
148
149/// The header octet of an aggregation packet: F is set if any aggregated F bit is, NRI is the
150/// maximum of the aggregated NRIs (RFC 6184 section 5.7).
151fn aggregation_header(packet_type: u8, nalus: &[Bytes]) -> u8 {
152    let mut forbidden = 0;
153    let mut ref_idc = 0;
154    for nalu in nalus {
155        if let Some(&header) = nalu.first() {
156            forbidden |= header & NALU_FORBIDDEN_BITMASK;
157            ref_idc = ref_idc.max(header & NALU_REF_IDC_BITMASK);
158        }
159    }
160    forbidden | ref_idc | packet_type
161}
162
163/// Checks the NAL units of an aggregate: each is a NAL unit (types 1 to 23) that fits the
164/// 16-bit size field.
165fn check_aggregated(nalus: &[&Bytes]) -> Result<()> {
166    if nalus.is_empty() {
167        return Err(Error::Other(
168            "an H.264 aggregation packet holds at least one NAL unit".to_owned(),
169        ));
170    }
171    for nalu in nalus {
172        let Some(&header) = nalu.first() else {
173            return Err(Error::ErrShortPacket);
174        };
175        if !is_nal_unit_type(header & NALU_TYPE_BITMASK) {
176            return Err(Error::NaluTypeIsNotHandled(header & NALU_TYPE_BITMASK));
177        }
178        if nalu.len() > u16::MAX as usize {
179            return Err(Error::NaluTooLarge(nalu.len()));
180        }
181    }
182    Ok(())
183}
184
185/// Builds a STAP-A payload (RFC 6184 section 5.7.1): the NAL units of one access unit, in
186/// decoding order.
187///
188/// # Errors
189///
190/// Fails without NAL units, for a unit over 65535 bytes, and for a unit that is not a NAL unit
191/// of types 1 to 23 (aggregates and fragments are not nested).
192pub fn stap_a(nalus: &[Bytes]) -> Result<Bytes> {
193    check_aggregated(&nalus.iter().collect::<Vec<_>>())?;
194    let mut out = BytesMut::with_capacity(
195        STAPA_HEADER_SIZE + nalus.iter().map(|nalu| 2 + nalu.len()).sum::<usize>(),
196    );
197    out.put_u8(aggregation_header(STAPA_NALU_TYPE, nalus));
198    for nalu in nalus {
199        out.put_u16(nalu.len() as u16);
200        out.put(&**nalu);
201    }
202    Ok(out.freeze())
203}
204
205/// Builds a STAP-B payload (RFC 6184 section 5.7.1): a STAP-A whose first NAL unit has the
206/// decoding order number `don`, each following one the number after it (modulo 65536).
207///
208/// # Errors
209///
210/// As [`stap_a`].
211pub fn stap_b(don: u16, nalus: &[Bytes]) -> Result<Bytes> {
212    check_aggregated(&nalus.iter().collect::<Vec<_>>())?;
213    let mut out = BytesMut::with_capacity(
214        STAPB_HEADER_SIZE + nalus.iter().map(|nalu| 2 + nalu.len()).sum::<usize>(),
215    );
216    out.put_u8(aggregation_header(STAPB_NALU_TYPE, nalus));
217    out.put_u16(don);
218    for nalu in nalus {
219        out.put_u16(nalu.len() as u16);
220        out.put(&**nalu);
221    }
222    Ok(out.freeze())
223}
224
225/// `don_diff(m, n)` of RFC 6184 section 5.5: positive when the NAL unit with DON `n` follows
226/// the one with DON `m` in decoding order, negative when it precedes it, zero when they share
227/// a DON.
228pub fn don_diff(m: u16, n: u16) -> i32 {
229    let (m, n) = (i32::from(m), i32::from(n));
230    if m == n {
231        0
232    } else if m < n && n - m < 32768 {
233        n - m
234    } else if m > n && m - n >= 32768 {
235        65536 - m + n
236    } else if m < n {
237        // n - m >= 32768
238        -(m + 65536 - n)
239    } else {
240        // m > n and m - n < 32768
241        -(m - n)
242    }
243}
244
245/// The width of the timestamp offset in a multi-time aggregation packet.
246#[derive(Debug, Copy, Clone, PartialEq, Eq)]
247pub enum MtapKind {
248    /// MTAP16: 16-bit timestamp offsets.
249    Mtap16,
250    /// MTAP24: 24-bit timestamp offsets.
251    Mtap24,
252}
253
254impl MtapKind {
255    fn nalu_type(self) -> u8 {
256        match self {
257            MtapKind::Mtap16 => MTAP16_NALU_TYPE,
258            MtapKind::Mtap24 => MTAP24_NALU_TYPE,
259        }
260    }
261
262    /// Bytes of timestamp offset in each aggregation unit.
263    fn offset_size(self) -> usize {
264        match self {
265            MtapKind::Mtap16 => 2,
266            MtapKind::Mtap24 => 3,
267        }
268    }
269}
270
271/// One NAL unit to place in a multi-time aggregation packet.
272#[derive(Debug, Clone, PartialEq, Eq)]
273pub struct MtapUnit {
274    /// The NAL unit's decoding order number.
275    pub don: u16,
276    /// The NAL unit's NALU-time: the RTP timestamp it would carry in a packet of its own.
277    pub timestamp: u32,
278    /// The NAL unit, header octet included.
279    pub nalu: Bytes,
280}
281
282/// Builds an MTAP16 or MTAP24 payload (RFC 6184 section 5.7.2) and the RTP timestamp its
283/// packet carries.
284///
285/// The DON base is the DON of the unit that is first in decoding order, each unit's DOND its
286/// distance from that; the packet's timestamp is the earliest NALU-time, whose unit gets the
287/// timestamp offset zero, and each other unit's offset is its NALU-time less that (modulo
288/// 2^32). The units are written in the order given, which should be decoding order.
289///
290/// # Errors
291///
292/// Fails without units, for a unit that is not a NAL unit of types 1 to 23 or is over 65535
293/// bytes, when a unit's DON is more than 255 after the first in decoding order, and when a
294/// timestamp offset does not fit the kind's 16 or 24 bits.
295pub fn mtap(kind: MtapKind, units: &[MtapUnit]) -> Result<(Bytes, u32)> {
296    check_aggregated(&units.iter().map(|unit| &unit.nalu).collect::<Vec<_>>())?;
297    // The first in decoding order: the unit no other unit precedes.
298    let mut don_base = units[0].don;
299    // The earliest NALU-time, by the same modulo comparison.
300    let mut timestamp = units[0].timestamp;
301    for unit in units {
302        if don_diff(don_base, unit.don) < 0 {
303            don_base = unit.don;
304        }
305        if (unit.timestamp.wrapping_sub(timestamp) as i32) < 0 {
306            timestamp = unit.timestamp;
307        }
308    }
309
310    let nalus: Vec<Bytes> = units.iter().map(|unit| unit.nalu.clone()).collect();
311    let mut out = BytesMut::with_capacity(
312        MTAP_HEADER_SIZE
313            + units
314                .iter()
315                .map(|unit| 3 + kind.offset_size() + unit.nalu.len())
316                .sum::<usize>(),
317    );
318    out.put_u8(aggregation_header(kind.nalu_type(), &nalus));
319    out.put_u16(don_base);
320    for unit in units {
321        let dond = u8::try_from(don_diff(don_base, unit.don)).map_err(|_| {
322            Error::Other(format!(
323                "MTAP: DON {} is more than 255 after the DON base {don_base}",
324                unit.don
325            ))
326        })?;
327        let offset = unit.timestamp.wrapping_sub(timestamp);
328        if offset >> (8 * kind.offset_size()) != 0 {
329            return Err(Error::Other(format!(
330                "MTAP: a timestamp offset of {offset} does not fit {} bits",
331                8 * kind.offset_size()
332            )));
333        }
334        out.put_u16(unit.nalu.len() as u16);
335        out.put_u8(dond);
336        match kind {
337            MtapKind::Mtap16 => out.put_u16(offset as u16),
338            MtapKind::Mtap24 => {
339                out.put_u8((offset >> 16) as u8);
340                out.put_u16(offset as u16);
341            }
342        }
343        out.put(&*unit.nalu);
344    }
345    Ok((out.freeze(), timestamp))
346}
347
348/// The packetization mode of RFC 6184 section 5.4.
349#[derive(Debug, Copy, Clone, PartialEq, Eq, Default)]
350enum PacketizationMode {
351    /// `packetization-mode=0`.
352    SingleNalUnit,
353    /// `packetization-mode=1`.
354    #[default]
355    NonInterleaved,
356    /// `packetization-mode=2`.
357    Interleaved,
358}
359
360/// H264Payloader payloads H264 packets
361#[derive(Default, Debug, Clone)]
362pub struct H264Payloader {
363    /// Parameter sets given in calls that held nothing else: sent, in the order given, ahead
364    /// of the access unit of the next call, so they carry its timestamp (RFC 6184 section 5.1).
365    held_parameter_sets: Vec<Bytes>,
366    mode: PacketizationMode,
367    /// Interleaved mode: the DON of the next NAL unit.
368    next_don: u16,
369}
370
371impl H264Payloader {
372    /// A payloader for the negotiated `packetization-mode` (RFC 6184 section 5.4).
373    ///
374    /// Mode 1 (non-interleaved) is the default: STAP-A for runs of small non-VCL NAL units
375    /// (parameter sets, SEI), FU-A for NAL units over the MTU, everything in the order given.
376    /// Mode 0 (single NAL unit) sends every NAL unit in a packet of its own and refuses one
377    /// that does not fit the MTU, since a mode-0 receiver cannot reassemble fragments. Mode 2
378    /// (interleaved) sends STAP-B aggregates and FU-B / FU-A fragments, every NAL unit with a
379    /// decoding order number that counts up by one from [`with_initial_don`](Self::with_initial_don),
380    /// in decoding order; single NAL unit packets, STAP-A and a leading FU-A are never used in
381    /// it (section 6.4). A value above 2 is not a packetization mode and is taken as mode 1;
382    /// [`try_with_packetization_mode`](Self::try_with_packetization_mode) refuses it instead.
383    pub fn with_packetization_mode(packetization_mode: u8) -> Self {
384        Self::try_with_packetization_mode(packetization_mode).unwrap_or_default()
385    }
386
387    /// As [`with_packetization_mode`](Self::with_packetization_mode), refusing a value that is
388    /// not 0, 1 or 2 (RFC 6184 section 8.1).
389    ///
390    /// # Errors
391    ///
392    /// Fails for a mode above 2.
393    pub fn try_with_packetization_mode(packetization_mode: u8) -> Result<Self> {
394        let mode = match packetization_mode {
395            0 => PacketizationMode::SingleNalUnit,
396            1 => PacketizationMode::NonInterleaved,
397            2 => PacketizationMode::Interleaved,
398            other => {
399                return Err(Error::Other(format!(
400                    "H.264 packetization-mode is 0, 1 or 2, not {other}"
401                )));
402            }
403        };
404        Ok(Self {
405            mode,
406            ..Default::default()
407        })
408    }
409
410    /// Interleaved mode: the decoding order number of the first NAL unit, which may be any
411    /// value (RFC 6184 section 5.5). 0 unless set.
412    pub fn with_initial_don(mut self, don: u16) -> Self {
413        self.next_don = don;
414        self
415    }
416
417    /// Whether the payloader sends this NAL unit: not an empty one, not an access unit
418    /// delimiter or filler data (never sent), and not a type that is reserved or is one of
419    /// this format's packet types (RFC 6184 section 5.4: such types are not sent; sent as a
420    /// "NAL unit", a type 24 to 29 would be read as an aggregate or a fragment).
421    fn is_sent(nalu: &Bytes) -> bool {
422        nalu.first().is_some_and(|&header| {
423            let nalu_type = header & NALU_TYPE_BITMASK;
424            is_nal_unit_type(nalu_type)
425                && nalu_type != AUD_NALU_TYPE
426                && nalu_type != FILLER_NALU_TYPE
427        })
428    }
429
430    /// Mode 0: each NAL unit as it is, or an error for one over the MTU.
431    fn emit_single_nal_unit(nalu: &Bytes, mtu: usize, payloads: &mut Vec<Bytes>) -> Result<()> {
432        if !Self::is_sent(nalu) {
433            return Ok(());
434        }
435        if nalu.len() > mtu {
436            return Err(Error::Other(format!(
437                "H.264 packetization-mode=0: a {}-byte NAL unit does not fit the {mtu}-byte MTU",
438                nalu.len()
439            )));
440        }
441        payloads.push(nalu.clone());
442        Ok(())
443    }
444
445    /// Emit a NALU as a single packet or fragment it via FU-A.
446    fn emit_single_or_fragment(nalu: &Bytes, mtu: usize, payloads: &mut Vec<Bytes>) {
447        if nalu.is_empty() {
448            return;
449        }
450
451        // Single NALU
452        if nalu.len() <= mtu {
453            payloads.push(nalu.clone());
454            return;
455        }
456
457        // FU-A fragmentation. The FU payload is the NAL unit without its header octet, whose
458        // F and NRI go in the FU indicator and whose type goes in the FU header (RFC 6184
459        // section 5.8). A NAL unit over the MTU always makes two fragments or more, so no
460        // fragment has both the start and the end bit.
461        let Some(max_fragment_size) = mtu.checked_sub(FUA_HEADER_SIZE).filter(|&size| size > 0)
462        else {
463            return;
464        };
465        // +---------------+      +---------------+
466        // |0|1|2|3|4|5|6|7|      |0|1|2|3|4|5|6|7|
467        // +-+-+-+-+-+-+-+-+      +-+-+-+-+-+-+-+-+
468        // |F|NRI|  Type   |      |S|E|R|  Type   |
469        // +---------------+      +---------------+
470        let indicator = (nalu[0] & (NALU_FORBIDDEN_BITMASK | NALU_REF_IDC_BITMASK)) | FUA_NALU_TYPE;
471        let nalu_type = nalu[0] & NALU_TYPE_BITMASK;
472        let data = &nalu[1..];
473        let last = data.len().div_ceil(max_fragment_size) - 1;
474        for (i, fragment) in data.chunks(max_fragment_size).enumerate() {
475            let mut out = BytesMut::with_capacity(FUA_HEADER_SIZE + fragment.len());
476            out.put_u8(indicator);
477            let mut fu_header = nalu_type;
478            if i == 0 {
479                fu_header |= FU_START_BITMASK;
480            } else if i == last {
481                fu_header |= FU_END_BITMASK;
482            }
483            out.put_u8(fu_header);
484            out.put(fragment);
485            payloads.push(out.freeze());
486        }
487    }
488
489    /// Interleaved mode: a NAL unit that does not fit a STAP-B, as an FU-B carrying its DON
490    /// followed by FU-As (RFC 6184 section 5.8). Always two fragments or more.
491    fn emit_fu_b(nalu: &Bytes, don: u16, mtu: usize, payloads: &mut Vec<Bytes>) {
492        let (Some(first_size), Some(next_size)) = (
493            mtu.checked_sub(FUB_HEADER_SIZE).filter(|&size| size > 0),
494            mtu.checked_sub(FUA_HEADER_SIZE).filter(|&size| size > 0),
495        ) else {
496            return;
497        };
498        let flags = nalu[0] & (NALU_FORBIDDEN_BITMASK | NALU_REF_IDC_BITMASK);
499        let nalu_type = nalu[0] & NALU_TYPE_BITMASK;
500        let data = &nalu[1..];
501        // A NAL unit is never sent in one FU: one that would fit the FU-B is cut in two.
502        let first_len = if data.len() <= first_size {
503            data.len().div_ceil(2)
504        } else {
505            first_size
506        };
507        let (first, rest) = data.split_at(first_len);
508
509        let mut out = BytesMut::with_capacity(FUB_HEADER_SIZE + first.len());
510        out.put_u8(flags | FUB_NALU_TYPE);
511        out.put_u8(FU_START_BITMASK | nalu_type);
512        out.put_u16(don);
513        out.put(first);
514        payloads.push(out.freeze());
515
516        // An FU payload may be empty, so there is always an end fragment.
517        let fragments = rest.len().div_ceil(next_size).max(1);
518        for i in 0..fragments {
519            let fragment = &rest[i * next_size..rest.len().min((i + 1) * next_size)];
520            let mut out = BytesMut::with_capacity(FUA_HEADER_SIZE + fragment.len());
521            out.put_u8(flags | FUA_NALU_TYPE);
522            out.put_u8(if i == fragments - 1 {
523                FU_END_BITMASK | nalu_type
524            } else {
525                nalu_type
526            });
527            out.put(fragment);
528            payloads.push(out.freeze());
529        }
530    }
531
532    /// Mode 1: the NAL units in the order given. A run of non-VCL NAL units that fits the MTU
533    /// goes in one STAP-A; a NAL unit over the MTU is fragmented.
534    fn payload_non_interleaved(
535        &mut self,
536        nalus: Vec<Bytes>,
537        mtu: usize,
538        payloads: &mut Vec<Bytes>,
539    ) {
540        let nalus: Vec<Bytes> = nalus.into_iter().filter(Self::is_sent).collect();
541        if nalus.is_empty() {
542            return;
543        }
544        // Parameter sets given on their own belong to the access unit that follows: they are
545        // kept, all of them and in order, and sent ahead of it.
546        let only_parameter_sets = nalus.iter().all(|nalu| {
547            let nalu_type = nalu[0] & NALU_TYPE_BITMASK;
548            nalu_type == SPS_NALU_TYPE || nalu_type == PPS_NALU_TYPE
549        });
550        let held_bytes: usize = self
551            .held_parameter_sets
552            .iter()
553            .chain(&nalus)
554            .map(Bytes::len)
555            .sum();
556        if only_parameter_sets
557            && self.held_parameter_sets.len() + nalus.len() <= MAX_HELD_PARAMETER_SETS
558            && held_bytes <= MAX_HELD_PARAMETER_SET_BYTES
559        {
560            self.held_parameter_sets.extend(nalus);
561            return;
562        }
563
564        fn flush(pending: &mut Vec<Bytes>, payloads: &mut Vec<Bytes>) {
565            match pending.len() {
566                0 => {}
567                // One NAL unit in a packet is a single NAL unit packet (RFC 6184 section 5.6).
568                1 => payloads.extend(pending.pop()),
569                _ => {
570                    let mut out = BytesMut::with_capacity(
571                        STAPA_HEADER_SIZE
572                            + pending.iter().map(|nalu| 2 + nalu.len()).sum::<usize>(),
573                    );
574                    out.put_u8(aggregation_header(STAPA_NALU_TYPE, pending));
575                    for nalu in pending.drain(..) {
576                        out.put_u16(nalu.len() as u16);
577                        out.put(nalu);
578                    }
579                    payloads.push(out.freeze());
580                }
581            }
582        }
583
584        let mut pending: Vec<Bytes> = vec![];
585        let mut pending_size = STAPA_HEADER_SIZE;
586        let held = std::mem::take(&mut self.held_parameter_sets);
587        for nalu in held.into_iter().chain(nalus) {
588            let unit_size = STAPA_NALU_LENGTH_SIZE + nalu.len();
589            let aggregated = !is_vcl_type(nalu[0] & NALU_TYPE_BITMASK)
590                && nalu.len() <= u16::MAX as usize
591                && STAPA_HEADER_SIZE + unit_size <= mtu;
592            if aggregated {
593                if pending_size + unit_size > mtu {
594                    flush(&mut pending, payloads);
595                    pending_size = STAPA_HEADER_SIZE;
596                }
597                pending_size += unit_size;
598                pending.push(nalu);
599            } else {
600                flush(&mut pending, payloads);
601                pending_size = STAPA_HEADER_SIZE;
602                Self::emit_single_or_fragment(&nalu, mtu, payloads);
603            }
604        }
605        flush(&mut pending, payloads);
606    }
607
608    /// Mode 2: the NAL units in the order given, each with the next DON. NAL units that fit
609    /// go in STAP-Bs, also alone (a single NAL unit packet is not allowed in this mode); the
610    /// others are fragmented, the first fragment an FU-B.
611    fn payload_interleaved(&mut self, nalus: Vec<Bytes>, mtu: usize, payloads: &mut Vec<Bytes>) {
612        fn flush(don: u16, pending: &mut Vec<Bytes>, payloads: &mut Vec<Bytes>) {
613            if pending.is_empty() {
614                return;
615            }
616            let mut out = BytesMut::with_capacity(
617                STAPB_HEADER_SIZE + pending.iter().map(|nalu| 2 + nalu.len()).sum::<usize>(),
618            );
619            out.put_u8(aggregation_header(STAPB_NALU_TYPE, pending));
620            out.put_u16(don);
621            for nalu in pending.drain(..) {
622                out.put_u16(nalu.len() as u16);
623                out.put(nalu);
624            }
625            payloads.push(out.freeze());
626        }
627
628        let mut pending: Vec<Bytes> = vec![];
629        let mut pending_don = self.next_don;
630        let mut pending_size = STAPB_HEADER_SIZE;
631        for nalu in nalus.into_iter().filter(Self::is_sent) {
632            let don = self.next_don;
633            self.next_don = self.next_don.wrapping_add(1);
634            let unit_size = STAPA_NALU_LENGTH_SIZE + nalu.len();
635            if nalu.len() <= u16::MAX as usize && STAPB_HEADER_SIZE + unit_size <= mtu {
636                if pending_size + unit_size > mtu {
637                    flush(pending_don, &mut pending, payloads);
638                    pending_size = STAPB_HEADER_SIZE;
639                }
640                if pending.is_empty() {
641                    pending_don = don;
642                }
643                pending_size += unit_size;
644                pending.push(nalu);
645            } else {
646                flush(pending_don, &mut pending, payloads);
647                pending_size = STAPB_HEADER_SIZE;
648                Self::emit_fu_b(&nalu, don, mtu, payloads);
649            }
650        }
651        flush(pending_don, &mut pending, payloads);
652    }
653}
654
655impl Payloader for H264Payloader {
656    /// Payload fragments a H264 packet across one or more byte arrays
657    fn payload(&mut self, mtu: usize, payload: &Bytes) -> Result<Vec<Bytes>> {
658        if payload.is_empty() || mtu == 0 {
659            return Ok(vec![]);
660        }
661
662        // The NAL units of the access unit, split at their Annex B start codes.
663        let nalus = annex_b_nal_units(payload);
664
665        let mut payloads = vec![];
666        match self.mode {
667            PacketizationMode::SingleNalUnit => {
668                for nalu in &nalus {
669                    Self::emit_single_nal_unit(nalu, mtu, &mut payloads)?;
670                }
671            }
672            PacketizationMode::NonInterleaved => {
673                self.payload_non_interleaved(nalus, mtu, &mut payloads)
674            }
675            PacketizationMode::Interleaved => self.payload_interleaved(nalus, mtu, &mut payloads),
676        }
677
678        Ok(payloads)
679    }
680
681    fn clone_to(&self) -> Box<dyn Payloader> {
682        Box::new(self.clone())
683    }
684}
685
686/// One NAL unit taken out of an RTP payload.
687#[derive(PartialEq, Eq, Debug, Clone)]
688pub struct H264NalUnit {
689    /// The NAL unit, header octet included, without a start code or a length prefix.
690    pub data: Bytes,
691    /// Its decoding order number, when its packet carried one: STAP-B, MTAP and a NAL unit
692    /// whose first fragment was an FU-B (RFC 6184 section 5.5).
693    pub don: Option<u16>,
694    /// Its timestamp offset from the packet's RTP timestamp, for a NAL unit of an MTAP: its
695    /// NALU-time is the packet's timestamp plus this, modulo 2^32 (RFC 6184 section 5.7.2).
696    pub timestamp_offset: Option<u32>,
697}
698
699impl H264NalUnit {
700    fn plain(data: Bytes) -> Self {
701        H264NalUnit {
702            data,
703            don: None,
704            timestamp_offset: None,
705        }
706    }
707
708    /// The NAL unit type: the low five bits of its header octet.
709    pub fn nalu_type(&self) -> u8 {
710        self.data.first().map_or(0, |b| b & NALU_TYPE_BITMASK)
711    }
712}
713
714/// The de-interleaving buffer never holds more NAL units than this, whatever
715/// `sprop-interleaving-depth` asks for: past it the NAL unit that is next in decoding order
716/// is passed on.
717pub const MAX_DEINTERLEAVING_NAL_UNITS: usize = 4096;
718/// Nor more bytes than this.
719pub const MAX_DEINTERLEAVING_BYTES: usize = 32 * 1024 * 1024;
720
721#[derive(PartialEq, Eq, Debug, Clone)]
722struct BufferedNalUnit {
723    unit: H264NalUnit,
724    don: u16,
725    /// `AbsDON` of RFC 6184 section 8.1 (`sprop-max-don-diff`): the DON unwrapped along the
726    /// reception order.
727    abs_don: i64,
728}
729
730/// The de-interleaving buffer of interleaved mode (RFC 6184 section 7.2.2): NAL units go in
731/// in reception order with their DON and come out in decoding order.
732///
733/// NAL units stay in the buffer until it holds `sprop-interleaving-depth + 1` VCL NAL units,
734/// or, when `sprop-max-don-diff` is given, until a NAL unit is more than that many DONs behind
735/// the latest one. They leave in ascending DON distance from the last one passed on.
736#[derive(PartialEq, Eq, Debug, Clone)]
737pub struct H264DeinterleavingBuffer {
738    /// N of section 7.2.2: `sprop-interleaving-depth` plus one.
739    vcl_capacity: usize,
740    max_don_diff: Option<i32>,
741    /// PDON: the DON of the last NAL unit passed on. `None` until one was: see
742    /// [`distance`](Self::distance).
743    previous_don: Option<u16>,
744    units: Vec<BufferedNalUnit>,
745    /// The DON and AbsDON of the NAL unit received last.
746    last_received: Option<(u16, i64)>,
747    bytes: usize,
748    /// `sprop-init-buf-time`, when signalled.
749    init_buf_time: Option<Duration>,
750    /// When the first NAL unit was stored ([`push_at`](Self::push_at)).
751    first_arrival: Option<Instant>,
752    /// Initial buffering ended by the depth or the DON spread (section 7.2.2).
753    initial_buffering_over: bool,
754    /// PDON starts at 0, as section 7.2.2 has it ([`with_literal_pdon`](Self::with_literal_pdon)).
755    literal_pdon: bool,
756}
757
758impl H264DeinterleavingBuffer {
759    /// A buffer for a stream with these `sprop-interleaving-depth` and `sprop-max-don-diff`
760    /// media type parameters (RFC 6184 section 8.1; both are 0 to 32767, and the second is
761    /// optional).
762    pub fn new(sprop_interleaving_depth: u16, sprop_max_don_diff: Option<u16>) -> Self {
763        H264DeinterleavingBuffer {
764            vcl_capacity: usize::from(sprop_interleaving_depth) + 1,
765            max_don_diff: sprop_max_don_diff.map(i32::from),
766            previous_don: None,
767            units: Vec::new(),
768            last_received: None,
769            bytes: 0,
770            init_buf_time: None,
771            first_arrival: None,
772            initial_buffering_over: false,
773            literal_pdon: false,
774        }
775    }
776
777    /// RFC 6184 section 7.2.2 as written: "Let PDON be a variable that is initialized to 0 at
778    /// the beginning of the RTP session". A NAL unit whose DON is 0 then has the largest DON
779    /// distance, so a stream numbered from DON 0 (or whose first DONs wrap through 0) has those
780    /// NAL units passed on after the others. Default off: until a NAL unit has been passed on,
781    /// PDON is the DON just before the earliest one buffered, which gives the RFC's order for
782    /// every other stream and decoding order for those.
783    pub fn with_literal_pdon(mut self, literal: bool) -> Self {
784        self.literal_pdon = literal;
785        self
786    }
787
788    /// The stream's `sprop-init-buf-time` (RFC 6184 section 8.1), in ticks of a 90 kHz
789    /// clock: "the initial buffering time that a receiver MUST wait before starting decoding".
790    pub fn with_init_buf_time(mut self, sprop_init_buf_time: u32) -> Self {
791        self.init_buf_time = Some(Duration::from_micros(
792            u64::from(sprop_init_buf_time) * 1_000_000 / 90_000,
793        ));
794        self
795    }
796
797    /// [`push`](Self::push) of a NAL unit that arrived at `now`, which starts the initial
798    /// buffering time on the first one.
799    pub fn push_at(&mut self, now: Instant, unit: H264NalUnit) -> Vec<H264NalUnit> {
800        if unit.don.is_some() {
801            self.first_arrival.get_or_insert(now);
802        }
803        self.push(unit)
804    }
805
806    /// Whether the receiver is still in initial buffering at `now` (RFC 6184 section 7.2.2),
807    /// and so is not to start decoding: until the buffer has held N VCL NAL units (N being
808    /// `sprop-interleaving-depth` plus one), or two NAL units more than `sprop-max-don-diff`
809    /// apart, or `sprop-init-buf-time` has passed since the first NAL unit arrived. The NAL
810    /// units the buffer passes on are in decoding order either way; this tells the decoder
811    /// when it may begin with them.
812    pub fn is_initial_buffering(&self, now: Instant) -> bool {
813        if self.initial_buffering_over {
814            return false;
815        }
816        match (self.init_buf_time, self.first_arrival) {
817            (Some(wait), Some(first)) => now.saturating_duration_since(first) < wait,
818            _ => true,
819        }
820    }
821
822    /// NAL units in the buffer.
823    pub fn len(&self) -> usize {
824        self.units.len()
825    }
826
827    /// Whether the buffer holds no NAL unit.
828    pub fn is_empty(&self) -> bool {
829        self.units.is_empty()
830    }
831
832    /// The DON distance of section 7.2.2 from the last NAL unit passed on (PDON).
833    ///
834    /// The RFC starts PDON at 0, which puts a NAL unit whose DON is 0 at the largest distance
835    /// there is: a stream numbered from 0 would have its first NAL unit passed on last. Until a
836    /// NAL unit has been passed on, PDON is taken here as the DON just before the earliest one
837    /// in the buffer (by AbsDON), so that the first NAL unit out is the first in decoding order
838    /// whatever DON the sender started from (section 5.5 lets it start anywhere).
839    fn distance(&self, don: u16) -> u32 {
840        let previous_don = self.previous_don.unwrap_or_else(|| {
841            if self.literal_pdon {
842                return 0;
843            }
844            self.units
845                .iter()
846                .min_by_key(|buffered| buffered.abs_don)
847                .map_or(0, |earliest| earliest.don.wrapping_sub(1))
848        });
849        if don > previous_don {
850            u32::from(don - previous_don)
851        } else {
852            65535 - u32::from(previous_don) + u32::from(don) + 1
853        }
854    }
855
856    fn vcl_count(&self) -> usize {
857        self.units
858            .iter()
859            .filter(|buffered| is_vcl_type(buffered.unit.nalu_type()))
860            .count()
861    }
862
863    /// Removes the NAL unit with the smallest DON distance. The buffer is not empty.
864    fn take_next(&mut self) -> BufferedNalUnit {
865        let index = (0..self.units.len())
866            .min_by_key(|&i| self.distance(self.units[i].don))
867            .unwrap_or(0);
868        let buffered = self.units.remove(index);
869        self.bytes -= buffered.unit.data.len();
870        buffered
871    }
872
873    /// Stores a NAL unit and returns the NAL units that are now due, in decoding order. A NAL
874    /// unit without a DON is not part of an interleaved stream and is returned as it is.
875    pub fn push(&mut self, unit: H264NalUnit) -> Vec<H264NalUnit> {
876        let Some(don) = unit.don else {
877            return vec![unit];
878        };
879        let abs_don = match self.last_received {
880            Some((last_don, last_abs)) => last_abs + i64::from(don_diff(last_don, don)),
881            None => i64::from(don),
882        };
883        self.last_received = Some((don, abs_don));
884        self.bytes += unit.data.len();
885        self.units.push(BufferedNalUnit { unit, don, abs_don });
886
887        let mut out = vec![];
888        let mut last_out = None;
889        // With N VCL NAL units or more in the buffer, NAL units leave until N - 1 are left.
890        // The distances are those from PDON as it was when the removal began.
891        if self.vcl_count() >= self.vcl_capacity {
892            self.initial_buffering_over = true;
893        }
894        while self.vcl_count() >= self.vcl_capacity {
895            let buffered = self.take_next();
896            last_out = Some(buffered.don);
897            out.push(buffered.unit);
898        }
899        // Every NAL unit more than sprop-max-don-diff behind the greatest AbsDON leaves too.
900        if let Some(max_don_diff) = self.max_don_diff {
901            let greatest = self.units.iter().map(|b| b.abs_don).max().unwrap_or(0);
902            loop {
903                let due = self
904                    .units
905                    .iter()
906                    .any(|b| greatest - b.abs_don > i64::from(max_don_diff));
907                if !due {
908                    break;
909                }
910                self.initial_buffering_over = true;
911                // In decoding order among those due.
912                let index = (0..self.units.len())
913                    .filter(|&i| greatest - self.units[i].abs_don > i64::from(max_don_diff))
914                    .min_by_key(|&i| self.distance(self.units[i].don))
915                    .unwrap_or(0);
916                let buffered = self.units.remove(index);
917                self.bytes -= buffered.unit.data.len();
918                last_out = Some(buffered.don);
919                out.push(buffered.unit);
920            }
921        }
922        // Bounded, whatever the stream's parameters say.
923        while self.units.len() > MAX_DEINTERLEAVING_NAL_UNITS
924            || self.bytes > MAX_DEINTERLEAVING_BYTES
925        {
926            let buffered = self.take_next();
927            last_out = Some(buffered.don);
928            out.push(buffered.unit);
929        }
930        if last_out.is_some() {
931            self.previous_don = last_out;
932        }
933        out
934    }
935
936    /// Empties the buffer, in decoding order: the end of the stream.
937    pub fn flush(&mut self) -> Vec<H264NalUnit> {
938        let mut buffered: Vec<(u32, BufferedNalUnit)> = self
939            .units
940            .iter()
941            .map(|b| (self.distance(b.don), b.clone()))
942            .collect();
943        self.units.clear();
944        self.bytes = 0;
945        buffered.sort_by_key(|(distance, _)| *distance);
946        let buffered: Vec<BufferedNalUnit> = buffered.into_iter().map(|(_, b)| b).collect();
947        if let Some(last) = buffered.last() {
948            self.previous_don = Some(last.don);
949        }
950        buffered.into_iter().map(|b| b.unit).collect()
951    }
952}
953
954/// H264Packet represents the H264 header that is stored in the payload of an RTP Packet
955#[derive(PartialEq, Eq, Debug, Default, Clone)]
956pub struct H264Packet {
957    /// Whether to emit AVCC length-prefixed output instead of Annex B start codes.
958    pub is_avc: bool,
959    fua_buffer: Option<BytesMut>,
960    /// The DON of the NAL unit being reassembled, when its first fragment was an FU-B.
961    fu_don: Option<u16>,
962    /// The sequence number of the last packet given with one.
963    last_sequence_number: Option<u16>,
964    deinterleaving: Option<H264DeinterleavingBuffer>,
965}
966
967impl H264Packet {
968    /// Receives an interleaved stream (`packetization-mode=2`) in decoding order: NAL units
969    /// that carry a DON go through `buffer` before [`depacketize`](Depacketizer::depacketize)
970    /// returns them (RFC 6184 section 7.2.2). Without this, NAL units come out in the order
971    /// their packets hold them, which is decoding order for modes 0 and 1.
972    pub fn with_deinterleaving(mut self, buffer: H264DeinterleavingBuffer) -> Self {
973        self.deinterleaving = Some(buffer);
974        self
975    }
976
977    /// The NAL units still in the de-interleaving buffer, in decoding order and in the output
978    /// format of [`depacketize`](Depacketizer::depacketize): for the end of the stream.
979    pub fn flush_deinterleaving(&mut self) -> Bytes {
980        let units = self
981            .deinterleaving
982            .as_mut()
983            .map(H264DeinterleavingBuffer::flush)
984            .unwrap_or_default();
985        self.format(&units)
986    }
987
988    /// As [`depacketize`](Depacketizer::depacketize), given the packet's RTP sequence number:
989    /// when a packet is missing before this one, the fragments collected so far are discarded
990    /// with the rest of their NAL unit, in place of a NAL unit with a hole in it (RFC 6184
991    /// section 5.8: a receiver discards the following fragmentation units of a NAL unit after
992    /// a lost one). Give the packets in sequence number order.
993    ///
994    /// # Errors
995    ///
996    /// As [`depacketize`](Depacketizer::depacketize).
997    pub fn depacketize_with_sequence_number(
998        &mut self,
999        sequence_number: u16,
1000        packet: &Bytes,
1001    ) -> Result<Bytes> {
1002        if let Some(last) = self.last_sequence_number
1003            && sequence_number != last.wrapping_add(1)
1004        {
1005            self.fua_buffer = None;
1006            self.fu_don = None;
1007        }
1008        self.last_sequence_number = Some(sequence_number);
1009        self.depacketize(packet)
1010    }
1011
1012    /// The NAL units a payload completes, with the decoding order number and timestamp offset
1013    /// its packet type gives them: one for a single NAL unit packet, several for an aggregate,
1014    /// none or one for a fragment. Reserved packet types yield nothing (RFC 6184 section 5.4:
1015    /// a receiver ignores them). The de-interleaving buffer is not involved.
1016    ///
1017    /// # Errors
1018    ///
1019    /// Fails for an empty payload, an aggregate or fragment cut short, a NAL unit size that
1020    /// runs past the payload, and a reassembly over [`MAX_FUA_NALU_SIZE`].
1021    pub fn nal_units(&mut self, packet: &Bytes) -> Result<Vec<H264NalUnit>> {
1022        // NALU Types
1023        // https://tools.ietf.org/html/rfc6184#section-5.4
1024        let Some(&b0) = packet.first() else {
1025            return Err(Error::ErrShortPacket);
1026        };
1027        let nalu_type = b0 & NALU_TYPE_BITMASK;
1028
1029        match nalu_type {
1030            // A single NAL unit packet, a header octet alone included (end of sequence, end
1031            // of stream).
1032            1..=23 => Ok(vec![H264NalUnit::plain(packet.clone())]),
1033            STAPA_NALU_TYPE | STAPB_NALU_TYPE => {
1034                let mut curr_offset = STAPA_HEADER_SIZE;
1035                let mut don = if nalu_type == STAPB_NALU_TYPE {
1036                    if packet.len() < STAPB_HEADER_SIZE {
1037                        return Err(Error::ErrShortPacket);
1038                    }
1039                    curr_offset = STAPB_HEADER_SIZE;
1040                    Some(u16::from_be_bytes([packet[1], packet[2]]))
1041                } else {
1042                    None
1043                };
1044                if curr_offset >= packet.len() {
1045                    // An aggregate holds at least one aggregation unit.
1046                    return Err(Error::ErrShortPacket);
1047                }
1048                let mut units = vec![];
1049                while curr_offset < packet.len() {
1050                    if packet.len() - curr_offset < STAPA_NALU_LENGTH_SIZE {
1051                        return Err(Error::ErrShortPacket);
1052                    }
1053                    let nalu_size =
1054                        ((packet[curr_offset] as usize) << 8) | packet[curr_offset + 1] as usize;
1055                    curr_offset += STAPA_NALU_LENGTH_SIZE;
1056
1057                    if packet.len() < curr_offset + nalu_size {
1058                        return Err(Error::StapASizeLargerThanBuffer(
1059                            nalu_size,
1060                            packet.len() - curr_offset,
1061                        ));
1062                    }
1063                    let data = packet.slice(curr_offset..curr_offset + nalu_size);
1064                    curr_offset += nalu_size;
1065                    // Each unit has the DON after the one before it, whether it is passed on
1066                    // or not. A unit that is not a NAL unit (empty, a nested aggregate or
1067                    // fragment, a reserved type) is ignored.
1068                    let unit_don = don;
1069                    don = don.map(|don| don.wrapping_add(1));
1070                    if data
1071                        .first()
1072                        .is_some_and(|b| is_nal_unit_type(b & NALU_TYPE_BITMASK))
1073                    {
1074                        units.push(H264NalUnit {
1075                            data,
1076                            don: unit_don,
1077                            timestamp_offset: None,
1078                        });
1079                    }
1080                }
1081                Ok(units)
1082            }
1083            MTAP16_NALU_TYPE | MTAP24_NALU_TYPE => {
1084                let offset_size = if nalu_type == MTAP16_NALU_TYPE { 2 } else { 3 };
1085                if packet.len() <= MTAP_HEADER_SIZE {
1086                    return Err(Error::ErrShortPacket);
1087                }
1088                let don_base = u16::from_be_bytes([packet[1], packet[2]]);
1089                let mut curr_offset = MTAP_HEADER_SIZE;
1090                let mut units = vec![];
1091                while curr_offset < packet.len() {
1092                    // NAL unit size, DOND and timestamp offset, then the NAL unit.
1093                    let unit_header = STAPA_NALU_LENGTH_SIZE + 1 + offset_size;
1094                    if packet.len() - curr_offset < unit_header {
1095                        return Err(Error::ErrShortPacket);
1096                    }
1097                    let nalu_size =
1098                        ((packet[curr_offset] as usize) << 8) | packet[curr_offset + 1] as usize;
1099                    let dond = packet[curr_offset + 2];
1100                    let timestamp_offset = packet[curr_offset + 3..curr_offset + unit_header]
1101                        .iter()
1102                        .fold(0u32, |offset, &b| (offset << 8) | u32::from(b));
1103                    curr_offset += unit_header;
1104                    if packet.len() < curr_offset + nalu_size {
1105                        return Err(Error::StapASizeLargerThanBuffer(
1106                            nalu_size,
1107                            packet.len() - curr_offset,
1108                        ));
1109                    }
1110                    let data = packet.slice(curr_offset..curr_offset + nalu_size);
1111                    curr_offset += nalu_size;
1112                    if data
1113                        .first()
1114                        .is_some_and(|b| is_nal_unit_type(b & NALU_TYPE_BITMASK))
1115                    {
1116                        units.push(H264NalUnit {
1117                            data,
1118                            // DON = (DONB + DOND) % 65536.
1119                            don: Some(don_base.wrapping_add(u16::from(dond))),
1120                            timestamp_offset: Some(timestamp_offset),
1121                        });
1122                    }
1123                }
1124                Ok(units)
1125            }
1126            FUA_NALU_TYPE | FUB_NALU_TYPE => {
1127                if packet.len() < FUA_HEADER_SIZE {
1128                    return Err(Error::ErrShortPacket);
1129                }
1130                // The R bit of the FU header is ignored (RFC 6184 section 5.8).
1131                let b1 = packet[1];
1132                let fragmented_nalu_type = b1 & NALU_TYPE_BITMASK;
1133                let start = b1 & FU_START_BITMASK != 0;
1134                let mut header_size = FUA_HEADER_SIZE;
1135
1136                if nalu_type == FUB_NALU_TYPE {
1137                    // An FU-B is the first fragment of a NAL unit and nothing else.
1138                    if !start || packet.len() < FUB_HEADER_SIZE {
1139                        self.fua_buffer = None;
1140                        self.fu_don = None;
1141                        return Err(Error::ErrShortPacket);
1142                    }
1143                    header_size = FUB_HEADER_SIZE;
1144                }
1145
1146                if start {
1147                    if is_nal_unit_type(fragmented_nalu_type) {
1148                        self.fua_buffer = Some(BytesMut::new());
1149                        self.fu_don = (nalu_type == FUB_NALU_TYPE)
1150                            .then(|| u16::from_be_bytes([packet[2], packet[3]]));
1151                    } else {
1152                        // A fragmented aggregate or fragment, or a reserved type: ignored,
1153                        // with the fragments that follow.
1154                        self.fua_buffer = None;
1155                        self.fu_don = None;
1156                    }
1157                }
1158                let Some(fua_buffer) = &mut self.fua_buffer else {
1159                    // A fragment whose start was lost cannot be reassembled into a NAL unit;
1160                    // drop it rather than splice it onto nothing.
1161                    return Ok(vec![]);
1162                };
1163
1164                // The FU payload may be empty.
1165                let fragment = &packet[header_size..];
1166                if fua_buffer.len() + fragment.len() > MAX_FUA_NALU_SIZE {
1167                    // Bounded: a peer that never sends the end fragment must not grow this
1168                    // without limit. Drop the partial NAL unit.
1169                    self.fua_buffer = None;
1170                    self.fu_don = None;
1171                    return Err(Error::ErrShortPacket);
1172                }
1173                fua_buffer.put(fragment);
1174
1175                if b1 & FU_END_BITMASK == 0 {
1176                    return Ok(vec![]);
1177                }
1178                // The NAL unit header: F and NRI from the FU indicator, the type from the FU
1179                // header.
1180                let mut data = BytesMut::with_capacity(1 + fua_buffer.len());
1181                data.put_u8(
1182                    (b0 & (NALU_FORBIDDEN_BITMASK | NALU_REF_IDC_BITMASK)) | fragmented_nalu_type,
1183                );
1184                if let Some(fua_buffer) = self.fua_buffer.take() {
1185                    data.put(fua_buffer);
1186                }
1187                Ok(vec![H264NalUnit {
1188                    data: data.freeze(),
1189                    don: self.fu_don.take(),
1190                    timestamp_offset: None,
1191                }])
1192            }
1193            // Types 0, 30 and 31 are reserved: ignored (RFC 6184 section 5.4).
1194            _ => Ok(vec![]),
1195        }
1196    }
1197
1198    /// NAL units as an Annex B byte stream, or length-prefixed for `is_avc`.
1199    fn format(&self, units: &[H264NalUnit]) -> Bytes {
1200        let mut payload =
1201            BytesMut::with_capacity(units.iter().map(|unit| 4 + unit.data.len()).sum());
1202        for unit in units {
1203            if self.is_avc {
1204                payload.put_u32(unit.data.len() as u32);
1205            } else {
1206                payload.put(&*ANNEXB_NALUSTART_CODE);
1207            }
1208            payload.put(&*unit.data);
1209        }
1210        payload.freeze()
1211    }
1212}
1213
1214impl Depacketizer for H264Packet {
1215    /// depacketize parses the passed byte slice and stores the result in the H264Packet this method is called upon
1216    fn depacketize(&mut self, packet: &Bytes) -> Result<Bytes> {
1217        let mut units = self.nal_units(packet)?;
1218        if let Some(buffer) = &mut self.deinterleaving {
1219            units = units
1220                .into_iter()
1221                .flat_map(|unit| buffer.push(unit))
1222                .collect();
1223        }
1224        Ok(self.format(&units))
1225    }
1226
1227    /// is_partition_head checks if this is the head of a packetized nalu stream.
1228    fn is_partition_head(&self, payload: &Bytes) -> bool {
1229        let Some(&b0) = payload.first() else {
1230            return false;
1231        };
1232
1233        if b0 & NALU_TYPE_BITMASK == FUA_NALU_TYPE || b0 & NALU_TYPE_BITMASK == FUB_NALU_TYPE {
1234            payload
1235                .get(1)
1236                .is_some_and(|fu_header| fu_header & FU_START_BITMASK != 0)
1237        } else {
1238            true
1239        }
1240    }
1241
1242    fn is_partition_tail(&self, marker: bool, _payload: &Bytes) -> bool {
1243        marker
1244    }
1245}