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 (owner decision, 2026-11-26; no erratum to RFC 6184 changes section 7.2 as of that
751/// date). [`with_literal_pdon(true)`](Self::with_literal_pdon) is the RFC's form.
752#[derive(PartialEq, Eq, Debug, Clone)]
753pub struct H264DeinterleavingBuffer {
754 /// N of section 7.2.2: `sprop-interleaving-depth` plus one.
755 vcl_capacity: usize,
756 max_don_diff: Option<i32>,
757 /// PDON: the DON of the last NAL unit passed on. `None` until one was: see
758 /// [`distance`](Self::distance).
759 previous_don: Option<u16>,
760 units: Vec<BufferedNalUnit>,
761 /// The DON and AbsDON of the NAL unit received last.
762 last_received: Option<(u16, i64)>,
763 bytes: usize,
764 /// `sprop-init-buf-time`, when signalled.
765 init_buf_time: Option<Duration>,
766 /// When the first NAL unit was stored ([`push_at`](Self::push_at)).
767 first_arrival: Option<Instant>,
768 /// Initial buffering ended by the depth or the DON spread (section 7.2.2).
769 initial_buffering_over: bool,
770 /// PDON starts at 0, as section 7.2.2 has it ([`with_literal_pdon`](Self::with_literal_pdon)).
771 literal_pdon: bool,
772}
773
774impl H264DeinterleavingBuffer {
775 /// A buffer for a stream with these `sprop-interleaving-depth` and `sprop-max-don-diff`
776 /// media type parameters (RFC 6184 section 8.1; both are 0 to 32767, and the second is
777 /// optional).
778 pub fn new(sprop_interleaving_depth: u16, sprop_max_don_diff: Option<u16>) -> Self {
779 H264DeinterleavingBuffer {
780 vcl_capacity: usize::from(sprop_interleaving_depth) + 1,
781 max_don_diff: sprop_max_don_diff.map(i32::from),
782 previous_don: None,
783 units: Vec::new(),
784 last_received: None,
785 bytes: 0,
786 init_buf_time: None,
787 first_arrival: None,
788 initial_buffering_over: false,
789 literal_pdon: false,
790 }
791 }
792
793 /// RFC 6184 section 7.2.2 as written: "Let PDON be a variable that is initialized to 0 at
794 /// the beginning of the RTP session". A NAL unit whose DON is 0 then has the largest DON
795 /// distance, so a stream numbered from DON 0 (or whose first DONs wrap through 0) has those
796 /// NAL units passed on after the others. Default off, which does not follow RFC 6184
797 /// section 7.2: until a NAL unit has been passed on, PDON is the DON just before the
798 /// earliest one buffered, which gives the RFC's order for every other stream and decoding
799 /// order for those.
800 pub fn with_literal_pdon(mut self, literal: bool) -> Self {
801 self.literal_pdon = literal;
802 self
803 }
804
805 /// The stream's `sprop-init-buf-time` (RFC 6184 section 8.1), in ticks of a 90 kHz
806 /// clock: "the initial buffering time that a receiver MUST wait before starting decoding".
807 pub fn with_init_buf_time(mut self, sprop_init_buf_time: u32) -> Self {
808 self.init_buf_time = Some(Duration::from_micros(
809 u64::from(sprop_init_buf_time) * 1_000_000 / 90_000,
810 ));
811 self
812 }
813
814 /// [`push`](Self::push) of a NAL unit that arrived at `now`, which starts the initial
815 /// buffering time on the first one.
816 pub fn push_at(&mut self, now: Instant, unit: H264NalUnit) -> Vec<H264NalUnit> {
817 if unit.don.is_some() {
818 self.first_arrival.get_or_insert(now);
819 }
820 self.push(unit)
821 }
822
823 /// Whether the receiver is still in initial buffering at `now` (RFC 6184 section 7.2.2),
824 /// and so is not to start decoding: until the buffer has held N VCL NAL units (N being
825 /// `sprop-interleaving-depth` plus one), or two NAL units more than `sprop-max-don-diff`
826 /// apart, or `sprop-init-buf-time` has passed since the first NAL unit arrived. The NAL
827 /// units the buffer passes on are in decoding order either way; this tells the decoder
828 /// when it may begin with them.
829 pub fn is_initial_buffering(&self, now: Instant) -> bool {
830 if self.initial_buffering_over {
831 return false;
832 }
833 match (self.init_buf_time, self.first_arrival) {
834 (Some(wait), Some(first)) => now.saturating_duration_since(first) < wait,
835 _ => true,
836 }
837 }
838
839 /// NAL units in the buffer.
840 pub fn len(&self) -> usize {
841 self.units.len()
842 }
843
844 /// Whether the buffer holds no NAL unit.
845 pub fn is_empty(&self) -> bool {
846 self.units.is_empty()
847 }
848
849 /// The DON distance of section 7.2.2 from the last NAL unit passed on (PDON).
850 ///
851 /// The RFC starts PDON at 0, which puts a NAL unit whose DON is 0 at the largest distance
852 /// there is: a stream numbered from 0 would have its first NAL unit passed on last. Until a
853 /// NAL unit has been passed on, PDON is taken here as the DON just before the earliest one
854 /// in the buffer (by AbsDON), so that the first NAL unit out is the first in decoding order
855 /// whatever DON the sender started from (section 5.5 lets it start anywhere).
856 fn distance(&self, don: u16) -> u32 {
857 let previous_don = self.previous_don.unwrap_or_else(|| {
858 if self.literal_pdon {
859 return 0;
860 }
861 self.units
862 .iter()
863 .min_by_key(|buffered| buffered.abs_don)
864 .map_or(0, |earliest| earliest.don.wrapping_sub(1))
865 });
866 if don > previous_don {
867 u32::from(don - previous_don)
868 } else {
869 65535 - u32::from(previous_don) + u32::from(don) + 1
870 }
871 }
872
873 fn vcl_count(&self) -> usize {
874 self.units
875 .iter()
876 .filter(|buffered| is_vcl_type(buffered.unit.nalu_type()))
877 .count()
878 }
879
880 /// Removes the NAL unit with the smallest DON distance. The buffer is not empty.
881 fn take_next(&mut self) -> BufferedNalUnit {
882 let index = (0..self.units.len())
883 .min_by_key(|&i| self.distance(self.units[i].don))
884 .unwrap_or(0);
885 let buffered = self.units.remove(index);
886 self.bytes -= buffered.unit.data.len();
887 buffered
888 }
889
890 /// Stores a NAL unit and returns the NAL units that are now due, in decoding order. A NAL
891 /// unit without a DON is not part of an interleaved stream and is returned as it is.
892 pub fn push(&mut self, unit: H264NalUnit) -> Vec<H264NalUnit> {
893 let Some(don) = unit.don else {
894 return vec![unit];
895 };
896 let abs_don = match self.last_received {
897 Some((last_don, last_abs)) => last_abs + i64::from(don_diff(last_don, don)),
898 None => i64::from(don),
899 };
900 self.last_received = Some((don, abs_don));
901 self.bytes += unit.data.len();
902 self.units.push(BufferedNalUnit { unit, don, abs_don });
903
904 let mut out = vec![];
905 let mut last_out = None;
906 // With N VCL NAL units or more in the buffer, NAL units leave until N - 1 are left.
907 // The distances are those from PDON as it was when the removal began.
908 if self.vcl_count() >= self.vcl_capacity {
909 self.initial_buffering_over = true;
910 }
911 while self.vcl_count() >= self.vcl_capacity {
912 let buffered = self.take_next();
913 last_out = Some(buffered.don);
914 out.push(buffered.unit);
915 }
916 // Every NAL unit more than sprop-max-don-diff behind the greatest AbsDON leaves too.
917 if let Some(max_don_diff) = self.max_don_diff {
918 let greatest = self.units.iter().map(|b| b.abs_don).max().unwrap_or(0);
919 loop {
920 let due = self
921 .units
922 .iter()
923 .any(|b| greatest - b.abs_don > i64::from(max_don_diff));
924 if !due {
925 break;
926 }
927 self.initial_buffering_over = true;
928 // In decoding order among those due.
929 let index = (0..self.units.len())
930 .filter(|&i| greatest - self.units[i].abs_don > i64::from(max_don_diff))
931 .min_by_key(|&i| self.distance(self.units[i].don))
932 .unwrap_or(0);
933 let buffered = self.units.remove(index);
934 self.bytes -= buffered.unit.data.len();
935 last_out = Some(buffered.don);
936 out.push(buffered.unit);
937 }
938 }
939 // Bounded, whatever the stream's parameters say.
940 while self.units.len() > MAX_DEINTERLEAVING_NAL_UNITS
941 || self.bytes > MAX_DEINTERLEAVING_BYTES
942 {
943 let buffered = self.take_next();
944 last_out = Some(buffered.don);
945 out.push(buffered.unit);
946 }
947 if last_out.is_some() {
948 self.previous_don = last_out;
949 }
950 out
951 }
952
953 /// Empties the buffer, in decoding order: the end of the stream.
954 pub fn flush(&mut self) -> Vec<H264NalUnit> {
955 let mut buffered: Vec<(u32, BufferedNalUnit)> = self
956 .units
957 .iter()
958 .map(|b| (self.distance(b.don), b.clone()))
959 .collect();
960 self.units.clear();
961 self.bytes = 0;
962 buffered.sort_by_key(|(distance, _)| *distance);
963 let buffered: Vec<BufferedNalUnit> = buffered.into_iter().map(|(_, b)| b).collect();
964 if let Some(last) = buffered.last() {
965 self.previous_don = Some(last.don);
966 }
967 buffered.into_iter().map(|b| b.unit).collect()
968 }
969}
970
971/// H264Packet represents the H264 header that is stored in the payload of an RTP Packet
972#[derive(PartialEq, Eq, Debug, Default, Clone)]
973pub struct H264Packet {
974 /// Whether to emit AVCC length-prefixed output instead of Annex B start codes.
975 pub is_avc: bool,
976 fua_buffer: Option<BytesMut>,
977 /// The DON of the NAL unit being reassembled, when its first fragment was an FU-B.
978 fu_don: Option<u16>,
979 /// The sequence number of the last packet given with one.
980 last_sequence_number: Option<u16>,
981 deinterleaving: Option<H264DeinterleavingBuffer>,
982}
983
984impl H264Packet {
985 /// Receives an interleaved stream (`packetization-mode=2`) in decoding order: NAL units
986 /// that carry a DON go through `buffer` before [`depacketize`](Depacketizer::depacketize)
987 /// returns them (RFC 6184 section 7.2.2). Without this, NAL units come out in the order
988 /// their packets hold them, which is decoding order for modes 0 and 1.
989 pub fn with_deinterleaving(mut self, buffer: H264DeinterleavingBuffer) -> Self {
990 self.deinterleaving = Some(buffer);
991 self
992 }
993
994 /// The NAL units still in the de-interleaving buffer, in decoding order and in the output
995 /// format of [`depacketize`](Depacketizer::depacketize): for the end of the stream.
996 pub fn flush_deinterleaving(&mut self) -> Bytes {
997 let units = self
998 .deinterleaving
999 .as_mut()
1000 .map(H264DeinterleavingBuffer::flush)
1001 .unwrap_or_default();
1002 self.format(&units)
1003 }
1004
1005 /// As [`depacketize`](Depacketizer::depacketize), given the packet's RTP sequence number:
1006 /// when a packet is missing before this one, the fragments collected so far are discarded
1007 /// with the rest of their NAL unit, in place of a NAL unit with a hole in it (RFC 6184
1008 /// section 5.8: a receiver discards the following fragmentation units of a NAL unit after
1009 /// a lost one). Give the packets in sequence number order.
1010 ///
1011 /// # Errors
1012 ///
1013 /// As [`depacketize`](Depacketizer::depacketize).
1014 pub fn depacketize_with_sequence_number(
1015 &mut self,
1016 sequence_number: u16,
1017 packet: &Bytes,
1018 ) -> Result<Bytes> {
1019 if let Some(last) = self.last_sequence_number
1020 && sequence_number != last.wrapping_add(1)
1021 {
1022 self.fua_buffer = None;
1023 self.fu_don = None;
1024 }
1025 self.last_sequence_number = Some(sequence_number);
1026 self.depacketize(packet)
1027 }
1028
1029 /// The NAL units a payload completes, with the decoding order number and timestamp offset
1030 /// its packet type gives them: one for a single NAL unit packet, several for an aggregate,
1031 /// none or one for a fragment. Reserved packet types yield nothing (RFC 6184 section 5.4:
1032 /// a receiver ignores them). The de-interleaving buffer is not involved.
1033 ///
1034 /// # Errors
1035 ///
1036 /// Fails for an empty payload, an aggregate or fragment cut short, a NAL unit size that
1037 /// runs past the payload, and a reassembly over [`MAX_FUA_NALU_SIZE`].
1038 pub fn nal_units(&mut self, packet: &Bytes) -> Result<Vec<H264NalUnit>> {
1039 // NALU Types
1040 // https://tools.ietf.org/html/rfc6184#section-5.4
1041 let Some(&b0) = packet.first() else {
1042 return Err(Error::ErrShortPacket);
1043 };
1044 let nalu_type = b0 & NALU_TYPE_BITMASK;
1045
1046 match nalu_type {
1047 // A single NAL unit packet, a header octet alone included (end of sequence, end
1048 // of stream).
1049 1..=23 => Ok(vec![H264NalUnit::plain(packet.clone())]),
1050 STAPA_NALU_TYPE | STAPB_NALU_TYPE => {
1051 let mut curr_offset = STAPA_HEADER_SIZE;
1052 let mut don = if nalu_type == STAPB_NALU_TYPE {
1053 if packet.len() < STAPB_HEADER_SIZE {
1054 return Err(Error::ErrShortPacket);
1055 }
1056 curr_offset = STAPB_HEADER_SIZE;
1057 Some(u16::from_be_bytes([packet[1], packet[2]]))
1058 } else {
1059 None
1060 };
1061 if curr_offset >= packet.len() {
1062 // An aggregate holds at least one aggregation unit.
1063 return Err(Error::ErrShortPacket);
1064 }
1065 let mut units = vec![];
1066 while curr_offset < packet.len() {
1067 if packet.len() - curr_offset < STAPA_NALU_LENGTH_SIZE {
1068 return Err(Error::ErrShortPacket);
1069 }
1070 let nalu_size =
1071 ((packet[curr_offset] as usize) << 8) | packet[curr_offset + 1] as usize;
1072 curr_offset += STAPA_NALU_LENGTH_SIZE;
1073
1074 if packet.len() < curr_offset + nalu_size {
1075 return Err(Error::StapASizeLargerThanBuffer(
1076 nalu_size,
1077 packet.len() - curr_offset,
1078 ));
1079 }
1080 let data = packet.slice(curr_offset..curr_offset + nalu_size);
1081 curr_offset += nalu_size;
1082 // Each unit has the DON after the one before it, whether it is passed on
1083 // or not. A unit that is not a NAL unit (empty, a nested aggregate or
1084 // fragment, a reserved type) is ignored.
1085 let unit_don = don;
1086 don = don.map(|don| don.wrapping_add(1));
1087 if data
1088 .first()
1089 .is_some_and(|b| is_nal_unit_type(b & NALU_TYPE_BITMASK))
1090 {
1091 units.push(H264NalUnit {
1092 data,
1093 don: unit_don,
1094 timestamp_offset: None,
1095 });
1096 }
1097 }
1098 Ok(units)
1099 }
1100 MTAP16_NALU_TYPE | MTAP24_NALU_TYPE => {
1101 let offset_size = if nalu_type == MTAP16_NALU_TYPE { 2 } else { 3 };
1102 if packet.len() <= MTAP_HEADER_SIZE {
1103 return Err(Error::ErrShortPacket);
1104 }
1105 let don_base = u16::from_be_bytes([packet[1], packet[2]]);
1106 let mut curr_offset = MTAP_HEADER_SIZE;
1107 let mut units = vec![];
1108 while curr_offset < packet.len() {
1109 // NAL unit size, DOND and timestamp offset, then the NAL unit.
1110 let unit_header = STAPA_NALU_LENGTH_SIZE + 1 + offset_size;
1111 if packet.len() - curr_offset < unit_header {
1112 return Err(Error::ErrShortPacket);
1113 }
1114 let nalu_size =
1115 ((packet[curr_offset] as usize) << 8) | packet[curr_offset + 1] as usize;
1116 let dond = packet[curr_offset + 2];
1117 let timestamp_offset = packet[curr_offset + 3..curr_offset + unit_header]
1118 .iter()
1119 .fold(0u32, |offset, &b| (offset << 8) | u32::from(b));
1120 curr_offset += unit_header;
1121 if packet.len() < curr_offset + nalu_size {
1122 return Err(Error::StapASizeLargerThanBuffer(
1123 nalu_size,
1124 packet.len() - curr_offset,
1125 ));
1126 }
1127 let data = packet.slice(curr_offset..curr_offset + nalu_size);
1128 curr_offset += nalu_size;
1129 if data
1130 .first()
1131 .is_some_and(|b| is_nal_unit_type(b & NALU_TYPE_BITMASK))
1132 {
1133 units.push(H264NalUnit {
1134 data,
1135 // DON = (DONB + DOND) % 65536.
1136 don: Some(don_base.wrapping_add(u16::from(dond))),
1137 timestamp_offset: Some(timestamp_offset),
1138 });
1139 }
1140 }
1141 Ok(units)
1142 }
1143 FUA_NALU_TYPE | FUB_NALU_TYPE => {
1144 if packet.len() < FUA_HEADER_SIZE {
1145 return Err(Error::ErrShortPacket);
1146 }
1147 // The R bit of the FU header is ignored (RFC 6184 section 5.8).
1148 let b1 = packet[1];
1149 let fragmented_nalu_type = b1 & NALU_TYPE_BITMASK;
1150 let start = b1 & FU_START_BITMASK != 0;
1151 let mut header_size = FUA_HEADER_SIZE;
1152
1153 if nalu_type == FUB_NALU_TYPE {
1154 // An FU-B is the first fragment of a NAL unit and nothing else.
1155 if !start || packet.len() < FUB_HEADER_SIZE {
1156 self.fua_buffer = None;
1157 self.fu_don = None;
1158 return Err(Error::ErrShortPacket);
1159 }
1160 header_size = FUB_HEADER_SIZE;
1161 }
1162
1163 if start {
1164 if is_nal_unit_type(fragmented_nalu_type) {
1165 self.fua_buffer = Some(BytesMut::new());
1166 self.fu_don = (nalu_type == FUB_NALU_TYPE)
1167 .then(|| u16::from_be_bytes([packet[2], packet[3]]));
1168 } else {
1169 // A fragmented aggregate or fragment, or a reserved type: ignored,
1170 // with the fragments that follow.
1171 self.fua_buffer = None;
1172 self.fu_don = None;
1173 }
1174 }
1175 let Some(fua_buffer) = &mut self.fua_buffer else {
1176 // A fragment whose start was lost cannot be reassembled into a NAL unit;
1177 // drop it rather than splice it onto nothing.
1178 return Ok(vec![]);
1179 };
1180
1181 // The FU payload may be empty.
1182 let fragment = &packet[header_size..];
1183 if fua_buffer.len() + fragment.len() > MAX_FUA_NALU_SIZE {
1184 // Bounded: a peer that never sends the end fragment must not grow this
1185 // without limit. Drop the partial NAL unit.
1186 self.fua_buffer = None;
1187 self.fu_don = None;
1188 return Err(Error::ErrShortPacket);
1189 }
1190 fua_buffer.put(fragment);
1191
1192 if b1 & FU_END_BITMASK == 0 {
1193 return Ok(vec![]);
1194 }
1195 // The NAL unit header: F and NRI from the FU indicator, the type from the FU
1196 // header.
1197 let mut data = BytesMut::with_capacity(1 + fua_buffer.len());
1198 data.put_u8(
1199 (b0 & (NALU_FORBIDDEN_BITMASK | NALU_REF_IDC_BITMASK)) | fragmented_nalu_type,
1200 );
1201 if let Some(fua_buffer) = self.fua_buffer.take() {
1202 data.put(fua_buffer);
1203 }
1204 Ok(vec![H264NalUnit {
1205 data: data.freeze(),
1206 don: self.fu_don.take(),
1207 timestamp_offset: None,
1208 }])
1209 }
1210 // Types 0, 30 and 31 are reserved: ignored (RFC 6184 section 5.4).
1211 _ => Ok(vec![]),
1212 }
1213 }
1214
1215 /// NAL units as an Annex B byte stream, or length-prefixed for `is_avc`.
1216 fn format(&self, units: &[H264NalUnit]) -> Bytes {
1217 let mut payload =
1218 BytesMut::with_capacity(units.iter().map(|unit| 4 + unit.data.len()).sum());
1219 for unit in units {
1220 if self.is_avc {
1221 payload.put_u32(unit.data.len() as u32);
1222 } else {
1223 payload.put(&*ANNEXB_NALUSTART_CODE);
1224 }
1225 payload.put(&*unit.data);
1226 }
1227 payload.freeze()
1228 }
1229}
1230
1231impl Depacketizer for H264Packet {
1232 /// depacketize parses the passed byte slice and stores the result in the H264Packet this method is called upon
1233 fn depacketize(&mut self, packet: &Bytes) -> Result<Bytes> {
1234 let mut units = self.nal_units(packet)?;
1235 if let Some(buffer) = &mut self.deinterleaving {
1236 units = units
1237 .into_iter()
1238 .flat_map(|unit| buffer.push(unit))
1239 .collect();
1240 }
1241 Ok(self.format(&units))
1242 }
1243
1244 /// is_partition_head checks if this is the head of a packetized nalu stream.
1245 fn is_partition_head(&self, payload: &Bytes) -> bool {
1246 let Some(&b0) = payload.first() else {
1247 return false;
1248 };
1249
1250 if b0 & NALU_TYPE_BITMASK == FUA_NALU_TYPE || b0 & NALU_TYPE_BITMASK == FUB_NALU_TYPE {
1251 payload
1252 .get(1)
1253 .is_some_and(|fu_header| fu_header & FU_START_BITMASK != 0)
1254 } else {
1255 true
1256 }
1257 }
1258
1259 fn is_partition_tail(&self, marker: bool, _payload: &Bytes) -> bool {
1260 marker
1261 }
1262
1263 fn has_key_frames(&self) -> bool {
1264 true
1265 }
1266
1267 /// A packet that carries the first slice of an IDR picture (`nal_unit_type` 5 with
1268 /// `first_mb_in_slice` 0, ITU-T H.264 sections 7.3.3 and 7.4.1.2.4: an IDR picture is
1269 /// decoded without reference to any earlier picture): as a single NAL unit packet, as the
1270 /// first fragment of an FU-A or FU-B, or inside an STAP-A or STAP-B behind nothing but
1271 /// parameter sets, SEI and access unit delimiters (RFC 6184 sections 5.6 to 5.8).
1272 /// Parameter sets sent in packets of their own before it belong to the same access unit
1273 /// (the same RTP timestamp) and are not what this names.
1274 fn is_key_frame_start(&self, payload: &Bytes) -> bool {
1275 /// Whether a NAL unit (header octet first) is the first slice of an IDR picture:
1276 /// `first_mb_in_slice` is ue(v), and zero is the single bit 1.
1277 fn first_idr_slice(unit: &[u8]) -> bool {
1278 unit.first()
1279 .is_some_and(|header| header & NALU_TYPE_BITMASK == IDR_NALU_TYPE)
1280 && unit.get(1).is_some_and(|slice| slice & 0x80 != 0)
1281 }
1282 let Some(&b0) = payload.first() else {
1283 return false;
1284 };
1285 match b0 & NALU_TYPE_BITMASK {
1286 IDR_NALU_TYPE => first_idr_slice(payload),
1287 kind @ (FUA_NALU_TYPE | FUB_NALU_TYPE) => {
1288 let data = if kind == FUA_NALU_TYPE {
1289 FUA_HEADER_SIZE
1290 } else {
1291 FUB_HEADER_SIZE
1292 };
1293 payload.get(1).is_some_and(|fu_header| {
1294 fu_header & FU_START_BITMASK != 0
1295 && fu_header & NALU_TYPE_BITMASK == IDR_NALU_TYPE
1296 }) && payload.get(data).is_some_and(|slice| slice & 0x80 != 0)
1297 }
1298 kind @ (STAPA_NALU_TYPE | STAPB_NALU_TYPE) => {
1299 let mut offset = if kind == STAPA_NALU_TYPE {
1300 STAPA_HEADER_SIZE
1301 } else {
1302 STAPB_HEADER_SIZE
1303 };
1304 while let Some(size) = payload.get(offset..offset + STAPA_NALU_LENGTH_SIZE) {
1305 let size = usize::from(u16::from_be_bytes([size[0], size[1]]));
1306 offset += STAPA_NALU_LENGTH_SIZE;
1307 let Some(unit) = payload.get(offset..offset + size) else {
1308 return false;
1309 };
1310 if first_idr_slice(unit) {
1311 return true;
1312 }
1313 match unit.first().map(|header| header & NALU_TYPE_BITMASK) {
1314 Some(SEI_NALU_TYPE | SPS_NALU_TYPE | PPS_NALU_TYPE | AUD_NALU_TYPE) => {}
1315 _ => return false,
1316 }
1317 offset += size;
1318 }
1319 false
1320 }
1321 _ => false,
1322 }
1323 }
1324}