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