rtci-rtp 0.4.1

RTP packets, header extensions (RFC 3550, RFC 8285) and codec payload formats for WebRTC
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
// Silence warning on `for i in 0..vec.len() { … }`:
#![allow(clippy::needless_range_loop)]

use super::*;

#[test]
fn fua_start_after_loss_boundary_discards_the_unfinished_nal() -> Result<()> {
    let old = Bytes::from([vec![0x65], vec![0x11; 400]].concat());
    let next = Bytes::from([vec![0x65], vec![0x22; 400]].concat());
    let mut payloader = H264Payloader::default();
    let fragments = payloader.payload(100, &old)?;
    assert!(fragments.len() > 2);
    let mut packet = H264Packet::default();
    for fragment in &fragments[..fragments.len() - 1] {
        assert!(packet.depacketize(fragment)?.is_empty());
    }
    let mut actual = Bytes::new();
    for fragment in payloader.payload(100, &next)? {
        actual = packet.depacketize(&fragment)?;
    }
    let expected = Bytes::from([ANNEXB_NALUSTART_CODE.as_ref(), next.as_ref()].concat());
    assert_eq!(
        actual.len(),
        expected.len(),
        "old fragments must not prefix the next IDR"
    );
    assert_eq!(actual, expected);
    Ok(())
}

#[test]
fn stapa_truncated_length_boundary_returns_an_error() {
    // A complete two-byte AUD NAL followed by only one byte of the next length.
    let payload = Bytes::from_static(&[0x78, 0, 2, 0x09, 0xf0, 0xff]);
    assert!(H264Packet::default().depacketize(&payload).is_err());
}

#[test]
fn test_h264_payload() -> Result<()> {
    let empty = Bytes::from_static(&[]);
    let small_payload = Bytes::from_static(&[0x90, 0x90, 0x90]);
    let multiple_payload = Bytes::from_static(&[0x00, 0x00, 0x01, 0x90, 0x00, 0x00, 0x01, 0x90]);
    // A NAL unit of type 1. (Upstream's vector had type 0, which is reserved and not sent:
    // RFC 6184 5.4.)
    let large_payload = Bytes::from_static(&[
        0x00, 0x00, 0x01, 0x01, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11,
        0x12, 0x13, 0x14, 0x15,
    ]);
    let large_payload_packetized = vec![
        Bytes::from_static(&[0x1c, 0x81, 0x01, 0x02, 0x03]),
        Bytes::from_static(&[0x1c, 0x01, 0x04, 0x05, 0x06]),
        Bytes::from_static(&[0x1c, 0x01, 0x07, 0x08, 0x09]),
        Bytes::from_static(&[0x1c, 0x01, 0x10, 0x11, 0x12]),
        Bytes::from_static(&[0x1c, 0x41, 0x13, 0x14, 0x15]),
    ];

    let mut pck = H264Payloader::default();

    // Positive MTU, empty payload
    let result = pck.payload(1, &empty)?;
    assert!(result.is_empty(), "Generated payload should be empty");

    // 0 MTU, small payload
    let result = pck.payload(0, &small_payload)?;
    assert_eq!(result.len(), 0, "Generated payload should be empty");

    // Positive MTU, small payload
    let result = pck.payload(1, &small_payload)?;
    assert_eq!(result.len(), 0, "Generated payload should be empty");

    // Positive MTU, small payload
    let result = pck.payload(5, &small_payload)?;
    assert_eq!(result.len(), 1, "Generated payload should be the 1");
    assert_eq!(
        result[0].len(),
        small_payload.len(),
        "Generated payload should be the same size as original payload size"
    );

    // Multiple NALU in a single payload
    let result = pck.payload(5, &multiple_payload)?;
    assert_eq!(result.len(), 2, "2 nal units should be broken out");
    for i in 0..2 {
        assert_eq!(
            result[i].len(),
            1,
            "Payload {} of 2 is packed incorrectly",
            i + 1,
        );
    }

    // Large Payload split across multiple RTP Packets
    let result = pck.payload(5, &large_payload)?;
    assert_eq!(
        result, large_payload_packetized,
        "FU-A packetization failed"
    );

    // Nalu type 9 or 12
    let small_payload2 = Bytes::from_static(&[0x09, 0x00, 0x00]);
    let result = pck.payload(5, &small_payload2)?;
    assert_eq!(result.len(), 0, "Generated payload should be empty");

    Ok(())
}

#[test]
fn test_h264_packet_unmarshal() -> Result<()> {
    let single_payload = Bytes::from_static(&[0x90, 0x90, 0x90]);
    let single_payload_unmarshaled =
        Bytes::from_static(&[0x00, 0x00, 0x00, 0x01, 0x90, 0x90, 0x90]);
    let single_payload_unmarshaled_avc =
        Bytes::from_static(&[0x00, 0x00, 0x00, 0x03, 0x90, 0x90, 0x90]);

    let large_payload = Bytes::from_static(&[
        0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10,
        0x11, 0x12, 0x13, 0x14, 0x15,
    ]);
    let large_payload_avc = Bytes::from_static(&[
        0x00, 0x00, 0x00, 0x10, 0x01, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10,
        0x11, 0x12, 0x13, 0x14, 0x15,
    ]);
    let large_payload_packetized = vec![
        Bytes::from_static(&[0x1c, 0x81, 0x01, 0x02, 0x03]),
        Bytes::from_static(&[0x1c, 0x01, 0x04, 0x05, 0x06]),
        Bytes::from_static(&[0x1c, 0x01, 0x07, 0x08, 0x09]),
        Bytes::from_static(&[0x1c, 0x01, 0x10, 0x11, 0x12]),
        Bytes::from_static(&[0x1c, 0x41, 0x13, 0x14, 0x15]),
    ];

    let single_payload_multi_nalu = Bytes::from_static(&[
        0x78, 0x00, 0x0f, 0x67, 0x42, 0xc0, 0x1f, 0x1a, 0x32, 0x35, 0x01, 0x40, 0x7a, 0x40, 0x3c,
        0x22, 0x11, 0xa8, 0x00, 0x05, 0x68, 0x1a, 0x34, 0xe3, 0xc8,
    ]);
    let single_payload_multi_nalu_unmarshaled = Bytes::from_static(&[
        0x00, 0x00, 0x00, 0x01, 0x67, 0x42, 0xc0, 0x1f, 0x1a, 0x32, 0x35, 0x01, 0x40, 0x7a, 0x40,
        0x3c, 0x22, 0x11, 0xa8, 0x00, 0x00, 0x00, 0x01, 0x68, 0x1a, 0x34, 0xe3, 0xc8,
    ]);
    let single_payload_multi_nalu_unmarshaled_avc = Bytes::from_static(&[
        0x00, 0x00, 0x00, 0x0f, 0x67, 0x42, 0xc0, 0x1f, 0x1a, 0x32, 0x35, 0x01, 0x40, 0x7a, 0x40,
        0x3c, 0x22, 0x11, 0xa8, 0x00, 0x00, 0x00, 0x05, 0x68, 0x1a, 0x34, 0xe3, 0xc8,
    ]);

    let incomplete_single_payload_multi_nalu = Bytes::from_static(&[
        0x78, 0x00, 0x0f, 0x67, 0x42, 0xc0, 0x1f, 0x1a, 0x32, 0x35, 0x01, 0x40, 0x7a, 0x40, 0x3c,
        0x22, 0x11,
    ]);

    let mut pkt = H264Packet::default();
    let mut avc_pkt = H264Packet {
        is_avc: true,
        ..Default::default()
    };

    let data = Bytes::from_static(&[]);
    let result = pkt.depacketize(&data);
    assert!(result.is_err(), "Unmarshal did not fail on nil payload");

    // Reserved types (0, 30, 31) are ignored, not an error (RFC 6184 5.4): nothing comes out.
    let data = Bytes::from_static(&[0x00, 0x00]);
    assert!(pkt.depacketize(&data)?.is_empty());

    let data = Bytes::from_static(&[0xFF, 0x00, 0x00]);
    assert!(pkt.depacketize(&data)?.is_empty());

    let result = pkt.depacketize(&incomplete_single_payload_multi_nalu);
    assert!(
        result.is_err(),
        "Unmarshal accepted a STAP-A packet with insufficient data"
    );

    let payload = pkt.depacketize(&single_payload)?;
    assert_eq!(
        payload, single_payload_unmarshaled,
        "Unmarshalling a single payload shouldn't modify the payload"
    );

    let payload = avc_pkt.depacketize(&single_payload)?;
    assert_eq!(
        payload, single_payload_unmarshaled_avc,
        "Unmarshalling a single payload into avc stream shouldn't modify the payload"
    );

    let mut large_payload_result = BytesMut::new();
    for p in &large_payload_packetized {
        let payload = pkt.depacketize(p)?;
        large_payload_result.put(&*payload.clone());
    }
    assert_eq!(
        large_payload_result.freeze(),
        large_payload,
        "Failed to unmarshal a large payload"
    );

    let mut large_payload_result_avc = BytesMut::new();
    for p in &large_payload_packetized {
        let payload = avc_pkt.depacketize(p)?;
        large_payload_result_avc.put(&*payload.clone());
    }
    assert_eq!(
        large_payload_result_avc.freeze(),
        large_payload_avc,
        "Failed to unmarshal a large payload into avc stream"
    );

    let payload = pkt.depacketize(&single_payload_multi_nalu)?;
    assert_eq!(
        payload, single_payload_multi_nalu_unmarshaled,
        "Failed to unmarshal a single packet with multiple NALUs"
    );

    let payload = avc_pkt.depacketize(&single_payload_multi_nalu)?;
    assert_eq!(
        payload, single_payload_multi_nalu_unmarshaled_avc,
        "Failed to unmarshal a single packet with multiple NALUs into avc stream"
    );

    Ok(())
}

#[test]
fn test_h264_partition_head_checker_is_partition_head() -> Result<()> {
    let h264 = H264Packet::default();
    let empty_nalu = Bytes::from_static(&[]);
    assert!(
        !h264.is_partition_head(&empty_nalu),
        "empty nalu must not be a partition head"
    );

    let single_nalu = Bytes::from_static(&[1, 0]);
    assert!(
        h264.is_partition_head(&single_nalu),
        "single nalu must be a partition head"
    );

    let stapa_nalu = Bytes::from_static(&[STAPA_NALU_TYPE, 0]);
    assert!(
        h264.is_partition_head(&stapa_nalu),
        "stapa nalu must be a partition head"
    );

    let fua_start_nalu = Bytes::from_static(&[FUA_NALU_TYPE, FU_START_BITMASK]);
    assert!(
        h264.is_partition_head(&fua_start_nalu),
        "fua start nalu must be a partition head"
    );

    let fua_end_nalu = Bytes::from_static(&[FUA_NALU_TYPE, FU_END_BITMASK]);
    assert!(
        !h264.is_partition_head(&fua_end_nalu),
        "fua end nalu must not be a partition head"
    );

    let fub_start_nalu = Bytes::from_static(&[FUB_NALU_TYPE, FU_START_BITMASK]);
    assert!(
        h264.is_partition_head(&fub_start_nalu),
        "fub start nalu must be a partition head"
    );

    let fub_end_nalu = Bytes::from_static(&[FUB_NALU_TYPE, FU_END_BITMASK]);
    assert!(
        !h264.is_partition_head(&fub_end_nalu),
        "fub end nalu must not be a partition head"
    );

    Ok(())
}

#[test]
fn test_h264_payloader_payload_sps_and_pps_handling() -> Result<()> {
    let mut pck = H264Payloader::default();
    let expected = vec![
        // The STAP-A header's NRI is the highest NRI aggregated (RFC 6184 5.7): 0 here.
        Bytes::from_static(&[
            0x18, 0x00, 0x03, 0x07, 0x00, 0x01, 0x00, 0x03, 0x08, 0x02, 0x03,
        ]),
        Bytes::from_static(&[0x05, 0x04, 0x05]),
    ];

    // When packetizing SPS and PPS are emitted with following NALU
    let res = pck.payload(1500, &Bytes::from_static(&[0x07, 0x00, 0x01]))?;
    assert!(res.is_empty(), "Generated payload should be empty");

    let res = pck.payload(1500, &Bytes::from_static(&[0x08, 0x02, 0x03]))?;
    assert!(res.is_empty(), "Generated payload should be empty");

    let actual = pck.payload(1500, &Bytes::from_static(&[0x05, 0x04, 0x05]))?;
    assert_eq!(actual, expected, "SPS and PPS aren't packed together");

    Ok(())
}

/// When the combined STAP-A of SPS + PPS exceeds the MTU, both should still
/// be emitted as individual (possibly FU-A fragmented) packets instead of
/// being silently dropped.
#[test]
fn test_h264_stap_a_exceeds_mtu_emits_individually() -> Result<()> {
    let mut pck = H264Payloader::default();

    // SPS: 3 bytes (NALU type 7)
    let sps = Bytes::from_static(&[0x07, 0xAA, 0xBB]);
    // PPS: 3 bytes (NALU type 8)
    let pps = Bytes::from_static(&[0x08, 0xCC, 0xDD]);

    let res = pck.payload(1500, &sps)?;
    assert!(res.is_empty(), "SPS alone should be stashed, not emitted");

    let res = pck.payload(1500, &pps)?;
    assert!(res.is_empty(), "PPS alone should be stashed, not emitted");

    // Use a tiny MTU so the STAP-A (1 + 2+3 + 2+3 = 11 bytes) exceeds it.
    // SPS and PPS individually are 3 bytes each, which fits in MTU=5.
    let result = pck.payload(5, &Bytes::from_static(&[0x05, 0x01, 0x02]))?;

    // Expect: SPS (3 bytes, fits), PPS (3 bytes, fits), then the IDR NALU (3 bytes, fits)
    assert_eq!(result.len(), 3, "expected SPS + PPS + IDR = 3 packets");
    assert_eq!(result[0], sps, "first packet should be the SPS NALU");
    assert_eq!(result[1], pps, "second packet should be the PPS NALU");
    assert_eq!(
        result[2],
        Bytes::from_static(&[0x05, 0x01, 0x02]),
        "third packet should be the IDR NALU"
    );

    Ok(())
}

/// When SPS or PPS are too large for a u16 length field (>65535 bytes), they
/// should be emitted via FU-A fragmentation using emit_single_or_fragment
/// rather than being packed into a STAP-A.
#[test]
fn test_h264_oversized_sps_uses_fua_fragmentation() -> Result<()> {
    let mut pck = H264Payloader::default();

    // Build a large SPS that genuinely exceeds u16::MAX (65535 bytes).
    // This ensures we actually hit the `sps_nalu.len() > u16::MAX` branch.
    let mut sps_data = vec![0x67]; // NALU type 7, with ref_idc bits set
    sps_data.extend(vec![0xAA; 70_000]);
    let sps = Bytes::from(sps_data); // 70001 bytes, well above u16::MAX threshold

    let pps = Bytes::from_static(&[0x68, 0xCC, 0xDD]); // NALU type 8, with ref_idc bits

    let res = pck.payload(1500, &sps)?;
    assert!(res.is_empty(), "SPS alone should be stashed");

    let res = pck.payload(1500, &pps)?;
    assert!(res.is_empty(), "PPS alone should be stashed");

    // Trigger emission with a small non-SPS/PPS NALU
    let result = pck.payload(1500, &Bytes::from_static(&[0x65, 0x01, 0x02]))?;

    // SPS (70001 bytes) exceeds u16::MAX, so it should be FU-A fragmented.
    // PPS (3 bytes) fits in a single packet.
    // IDR (3 bytes) fits in a single packet.
    assert!(
        result.len() >= 3,
        "expected at least 3 packets (fragmented SPS + PPS + IDR), got {}",
        result.len()
    );

    // Verify the first packet is a FU-A start fragment of the SPS
    assert_eq!(
        result[0][0] & NALU_TYPE_BITMASK,
        FUA_NALU_TYPE,
        "first packet should be a FU-A fragment"
    );
    assert_ne!(
        result[0][1] & FU_START_BITMASK,
        0,
        "first FU-A fragment should have start bit set"
    );

    Ok(())
}

/// The emit_single_or_fragment helper should pass through small NALUs directly
/// and fragment large ones via FU-A.
#[test]
fn test_h264_emit_single_or_fragment_small_nalu() {
    let nalu = Bytes::from_static(&[0x65, 0x01, 0x02, 0x03]);
    let mut payloads = vec![];
    H264Payloader::emit_single_or_fragment(&nalu, 10, &mut payloads);
    assert_eq!(payloads.len(), 1, "small NALU should emit as single packet");
    assert_eq!(payloads[0], nalu);
}

#[test]
fn test_h264_emit_single_or_fragment_large_nalu() {
    let mut data = vec![0x65]; // IDR NALU type
    data.extend(vec![0xBB; 20]);
    let nalu = Bytes::from(data);
    let mut payloads = vec![];
    H264Payloader::emit_single_or_fragment(&nalu, 10, &mut payloads);
    assert!(
        payloads.len() > 1,
        "large NALU should be FU-A fragmented into multiple packets"
    );
    // First fragment should have FU-A type and start bit
    assert_eq!(payloads[0][0] & NALU_TYPE_BITMASK, FUA_NALU_TYPE);
    assert_ne!(payloads[0][1] & FU_START_BITMASK, 0);
    // Last fragment should have end bit
    let last = payloads.last().unwrap();
    assert_ne!(last[1] & FU_END_BITMASK, 0);
}

#[test]
fn test_h264_emit_single_or_fragment_empty_nalu() {
    let nalu = Bytes::new();
    let mut payloads = vec![];
    H264Payloader::emit_single_or_fragment(&nalu, 10, &mut payloads);
    assert!(payloads.is_empty(), "empty NALU should produce no packets");
}

/// FU-A reassembly is bounded: a stream of start + middle fragments with no end stops being
/// buffered at `MAX_FUA_NALU_SIZE`, and a fragment whose start was lost is dropped.
#[test]
fn test_h264_fua_reassembly_is_bounded_and_needs_a_start() -> Result<()> {
    let mut pck = H264Packet::default();
    let chunk = vec![0xaa; 60_000];
    let fragment = |header: u8| {
        let mut p = vec![FUA_NALU_TYPE, header];
        p.extend_from_slice(&chunk);
        Bytes::from(p)
    };

    // A middle fragment with no start before it is dropped.
    assert!(pck.depacketize(&fragment(0x05))?.is_empty());
    assert!(pck.fua_buffer.is_none());

    // Start, then middles until well past the cap: the buffer never exceeds it.
    pck.depacketize(&fragment(FU_START_BITMASK | 0x05))?;
    for _ in 0..((MAX_FUA_NALU_SIZE / chunk.len()) + 10) {
        let _ = pck.depacketize(&fragment(0x05));
        assert!(
            pck.fua_buffer
                .as_ref()
                .is_none_or(|b| b.len() <= MAX_FUA_NALU_SIZE),
            "FU-A buffer grew past its cap"
        );
    }
    Ok(())
}

/// The Annex B splitter finds the start codes the byte-at-a-time scan it replaced found
/// (webrtc-rs/rtc#336 by @g4lb): three- and four-byte codes, longer runs of zeros before one
/// (the trailing zeros of the NAL unit before it go with the code), codes at the very start and
/// end, codes with nothing between them, and no code at all. Inputs dense in zeros and ones, so
/// every arrangement of them is met.
#[test]
fn annex_b_nal_units_are_those_a_byte_scan_finds() {
    fn byte_scan(payload: &Bytes) -> Vec<Bytes> {
        let next = |start: usize| -> Option<(usize, usize)> {
            let mut zeros = 0;
            for (i, &b) in payload[start..].iter().enumerate() {
                if b == 0 {
                    zeros += 1;
                    continue;
                } else if b == 1 && zeros >= 2 {
                    return Some((start + i - zeros, zeros + 1));
                }
                zeros = 0;
            }
            None
        };
        let Some((mut at, mut len)) = next(0) else {
            return vec![payload.clone()];
        };
        let mut nalus = vec![];
        loop {
            let nalu_start = at + len;
            match next(nalu_start) {
                Some((a, l)) => {
                    nalus.push(payload.slice(nalu_start..a));
                    (at, len) = (a, l);
                }
                None => {
                    nalus.push(payload.slice(nalu_start..));
                    return nalus;
                }
            }
        }
    }

    let mut state = 0x2545_f491_4f6c_dd1du64;
    let mut byte = || {
        state ^= state << 13;
        state ^= state >> 7;
        state ^= state << 17;
        match state % 8 {
            0..=3 => 0,
            4 | 5 => 1,
            _ => (state >> 8) as u8,
        }
    };
    for len in 0..48 {
        for _ in 0..2_000 {
            let payload = Bytes::from((0..len).map(|_| byte()).collect::<Vec<u8>>());
            assert_eq!(
                annex_b_nal_units(&payload),
                byte_scan(&payload),
                "{:02x?}",
                &payload[..]
            );
        }
    }
}