rtci-rtp 0.2.0

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
507
use super::*;

#[test]
fn test_vp9_packet_unmarshal() -> Result<()> {
    let tests = vec![
        (
            "Empty",
            Bytes::from_static(&[]),
            Vp9Packet::default(),
            Bytes::new(),
            Some(Error::ErrShortPacket),
        ),
        (
            "NonFlexible",
            Bytes::from_static(&[0x00, 0xAA]),
            Vp9Packet::default(),
            Bytes::from_static(&[0xAA]),
            None,
        ),
        (
            "NonFlexiblePictureID",
            Bytes::from_static(&[0x80, 0x02, 0xAA]),
            Vp9Packet {
                i: true,
                picture_id: 0x02,
                ..Default::default()
            },
            Bytes::from_static(&[0xAA]),
            None,
        ),
        (
            "NonFlexiblePictureIDExt",
            Bytes::from_static(&[0x80, 0x81, 0xFF, 0xAA]),
            Vp9Packet {
                i: true,
                picture_id: 0x01FF,
                picture_id_15_bits: true,
                ..Default::default()
            },
            Bytes::from_static(&[0xAA]),
            None,
        ),
        (
            "NonFlexiblePictureIDExt_ShortPacket0",
            Bytes::from_static(&[0x80, 0x81]),
            Vp9Packet::default(),
            Bytes::new(),
            Some(Error::ErrShortPacket),
        ),
        (
            "NonFlexiblePictureIDExt_ShortPacket1",
            Bytes::from_static(&[0x80]),
            Vp9Packet::default(),
            Bytes::new(),
            Some(Error::ErrShortPacket),
        ),
        (
            "NonFlexibleLayerIndicePictureID",
            Bytes::from_static(&[0xA0, 0x02, 0x23, 0x01, 0xAA]),
            Vp9Packet {
                i: true,
                l: true,
                picture_id: 0x02,
                tid: 0x01,
                sid: 0x01,
                d: true,
                tl0picidx: 0x01,
                ..Default::default()
            },
            Bytes::from_static(&[0xAA]),
            None,
        ),
        (
            "FlexibleLayerIndicePictureID",
            Bytes::from_static(&[0xB0, 0x02, 0x23, 0x01, 0xAA]),
            Vp9Packet {
                f: true,
                i: true,
                l: true,
                picture_id: 0x02,
                tid: 0x01,
                sid: 0x01,
                d: true,
                ..Default::default()
            },
            Bytes::from_static(&[0x01, 0xAA]),
            None,
        ),
        (
            "NonFlexibleLayerIndicePictureID_ShortPacket0",
            Bytes::from_static(&[0xA0, 0x02, 0x23]),
            Vp9Packet::default(),
            Bytes::new(),
            Some(Error::ErrShortPacket),
        ),
        (
            "NonFlexibleLayerIndicePictureID_ShortPacket1",
            Bytes::from_static(&[0xA0, 0x02]),
            Vp9Packet::default(),
            Bytes::new(),
            Some(Error::ErrShortPacket),
        ),
        (
            "FlexiblePictureIDRefIndex",
            Bytes::from_static(&[0xD0, 0x02, 0x03, 0x04, 0xAA]),
            Vp9Packet {
                i: true,
                p: true,
                f: true,
                picture_id: 0x02,
                pdiff: vec![0x01, 0x02],
                ..Default::default()
            },
            Bytes::from_static(&[0xAA]),
            None,
        ),
        (
            "FlexiblePictureIDRefIndex_TooManyPDiff",
            Bytes::from_static(&[0xD0, 0x02, 0x03, 0x05, 0x07, 0x09, 0x10, 0xAA]),
            Vp9Packet::default(),
            Bytes::new(),
            Some(Error::ErrTooManyPDiff),
        ),
        (
            "FlexiblePictureIDRefIndexNoPayload",
            Bytes::from_static(&[0xD0, 0x02, 0x03, 0x04]),
            Vp9Packet {
                i: true,
                p: true,
                f: true,
                picture_id: 0x02,
                pdiff: vec![0x01, 0x02],
                ..Default::default()
            },
            Bytes::from_static(&[]),
            None,
        ),
        (
            "FlexiblePictureIDRefIndex_ShortPacket0",
            Bytes::from_static(&[0xD0, 0x02, 0x03]),
            Vp9Packet::default(),
            Bytes::new(),
            Some(Error::ErrShortPacket),
        ),
        (
            "FlexiblePictureIDRefIndex_ShortPacket1",
            Bytes::from_static(&[0xD0, 0x02]),
            Vp9Packet::default(),
            Bytes::new(),
            Some(Error::ErrShortPacket),
        ),
        (
            "FlexiblePictureIDRefIndex_ShortPacket2",
            Bytes::from_static(&[0xD0]),
            Vp9Packet::default(),
            Bytes::new(),
            Some(Error::ErrShortPacket),
        ),
        (
            "ScalabilityStructureResolutionsNoPayload",
            Bytes::from_static(&[
                0x0A,
                (1 << 5) | (1 << 4), // NS:1 Y:1 G:0
                (640 >> 8) as u8,
                (640 & 0xff) as u8,
                (360 >> 8) as u8,
                (360 & 0xff) as u8,
                (1280 >> 8) as u8,
                (1280 & 0xff) as u8,
                (720 >> 8) as u8,
                (720 & 0xff) as u8,
            ]),
            Vp9Packet {
                b: true,
                v: true,
                ns: 1,
                y: true,
                g: false,
                ng: 0,
                width: vec![640, 1280],
                height: vec![360, 720],
                ..Default::default()
            },
            Bytes::new(),
            None,
        ),
        (
            "ScalabilityStructureNoPayload",
            Bytes::from_static(&[
                0x0A,
                (1 << 5) | (1 << 3), // NS:1 Y:0 G:1
                2,
                (1 << 4),            // T:0 U:1 R:0 -
                (2 << 5) | (1 << 2), // T:2 U:0 R:1 -
                33,
            ]),
            Vp9Packet {
                b: true,
                v: true,
                ns: 1,
                y: false,
                g: true,
                ng: 2,
                pgtid: vec![0, 2],
                pgu: vec![true, false],
                pgpdiff: vec![vec![], vec![33]],
                ..Default::default()
            },
            Bytes::new(),
            None,
        ),
    ];

    for (name, b, pkt, expected, err) in tests {
        let mut p = Vp9Packet::default();

        if let Some(expected) = err {
            if let Err(actual) = p.depacketize(&b) {
                assert_eq!(
                    expected, actual,
                    "{name}: expected {expected}, but got {actual}"
                );
            } else {
                panic!("{name}: expected error, but got passed");
            }
        } else {
            let payload = p.depacketize(&b)?;
            assert_eq!(pkt, p, "{name}: expected {pkt:?}, but got {p:?}");
            assert_eq!(payload, expected);
        }
    }

    Ok(())
}

#[test]
fn test_vp9_payloader_payload() -> Result<()> {
    let mut rands = vec![];
    for r0 in (8692..).take(10) {
        rands.push(vec![(r0 >> 8) as u8 | 0x80, (r0 & 0xFF) as u8]);
    }

    let tests = vec![
        ("NilPayload", vec![Bytes::new()], 100, vec![]),
        ("SmallMTU", vec![Bytes::from(vec![0x00, 0x00])], 1, vec![]),
        (
            "NegativeMTU",
            vec![Bytes::from(vec![0x00, 0x00])],
            0,
            vec![],
        ),
        (
            "OnePacket",
            vec![Bytes::from(vec![0x01, 0x02])],
            10,
            vec![Bytes::from(vec![
                0x9C,
                rands[0][0],
                rands[0][1],
                0x01,
                0x02,
            ])],
        ),
        (
            "TwoPackets",
            vec![Bytes::from(vec![0x01, 0x02])],
            4,
            vec![
                Bytes::from(vec![0x98, rands[0][0], rands[0][1], 0x01]),
                Bytes::from(vec![0x94, rands[0][0], rands[0][1], 0x02]),
            ],
        ),
        (
            "ThreePackets",
            vec![Bytes::from(vec![0x01, 0x02, 0x03])],
            4,
            vec![
                Bytes::from(vec![0x98, rands[0][0], rands[0][1], 0x01]),
                Bytes::from(vec![0x90, rands[0][0], rands[0][1], 0x02]),
                Bytes::from(vec![0x94, rands[0][0], rands[0][1], 0x03]),
            ],
        ),
        (
            "TwoFramesFourPackets",
            vec![Bytes::from(vec![0x01, 0x02, 0x03]), Bytes::from(vec![0x04])],
            5,
            vec![
                Bytes::from(vec![0x98, rands[0][0], rands[0][1], 0x01, 0x02]),
                Bytes::from(vec![0x94, rands[0][0], rands[0][1], 0x03]),
                // Not a VP9 frame and not the first of the stream: nothing says it does not
                // depend on what came before, so P=1 with the reference index flexible mode
                // then requires (P_DIFF 1, N 0). It used to go out as P=0.
                Bytes::from(vec![0xDC, rands[1][0], rands[1][1], 0x02, 0x04]),
            ],
        ),
    ];

    for (name, bs, mtu, expected) in tests {
        let mut pck = Vp9Payloader {
            initial_picture_id_fn: Some(Arc::new(|| -> u16 { 8692 })),
            ..Default::default()
        };

        let mut actual = vec![];
        for b in &bs {
            actual.extend(pck.payload(mtu, b)?);
        }
        assert_eq!(actual, expected, "{name}: Payloaded packet");
    }

    //"PictureIDOverflow"
    {
        let mut pck = Vp9Payloader {
            initial_picture_id_fn: Some(Arc::new(|| -> u16 { 8692 })),
            ..Default::default()
        };
        let mut p_prev = Vp9Packet::default();
        for i in 0..0x8000 {
            let res = pck.payload(5, &Bytes::from_static(&[0x01]))?;
            let mut p = Vp9Packet::default();
            p.depacketize(&res[0])?;

            if i > 0 {
                if p_prev.picture_id == 0x7FFF {
                    assert_eq!(
                        p.picture_id, 0,
                        "Picture ID next to 0x7FFF must be 0, got {}",
                        p.picture_id
                    );
                } else if p_prev.picture_id + 1 != p.picture_id {
                    panic!(
                        "Picture ID next must be incremented by 1: {} -> {}",
                        p_prev.picture_id, p.picture_id,
                    );
                }
            }

            p_prev = p;
        }
    }

    Ok(())
}

#[test]
fn test_vp9_partition_head_checker_is_partition_head() -> Result<()> {
    let vp9 = Vp9Packet::default();

    //"SmallPacket"
    assert!(
        !vp9.is_partition_head(&Bytes::new()),
        "Small packet should not be the head of a new partition"
    );

    //"NormalPacket"
    assert!(
        vp9.is_partition_head(&Bytes::from_static(&[0x18, 0x00, 0x00])),
        "VP9 RTP packet with B flag should be head of a new partition"
    );
    assert!(
        !vp9.is_partition_head(&Bytes::from_static(&[0x10, 0x00, 0x00])),
        "VP9 RTP packet without B flag should not be head of a new partition"
    );

    Ok(())
}

/// A depacketizer is used for a whole stream. The reference indices of one flexible-mode packet
/// used to stay in `pdiff`, so after two packets every further one failed with
/// `ErrTooManyPDiff`; and each scalability structure appended its picture group to the last
/// one's, without bound.
#[test]
fn test_vp9_per_picture_state_does_not_accumulate() -> Result<()> {
    let mut pck = Vp9Packet::default();
    // I=1, P=1, F=1; picture ID 5; two P_DIFFs (1 with N=1, then 1 with N=0); one payload
    // byte. (F only counts with I=1, RFC 9628 4.2.)
    let flexible = Bytes::from_static(&[0xd0, 0x05, 0x03, 0x02, 0xaa]);
    for _ in 0..10 {
        let payload = pck.depacketize(&flexible)?;
        assert_eq!(&payload[..], &[0xaa]);
        assert_eq!(pck.pdiff, vec![1, 1]);
    }

    // V=1; SS with N_S=0, Y=0, G=1 (bit 3 of `N_S|Y|G|-|-|-|`, RFC 9628 4.2.1), N_G=255
    // pictures (T=0, U=0, R=0 each).
    let mut ss = vec![0x02, 0x08, 0xff];
    ss.extend(std::iter::repeat_n(0x00, 255));
    ss.push(0xaa);
    let ss = Bytes::from(ss);
    for _ in 0..10 {
        pck.depacketize(&ss)?;
        assert_eq!(pck.pgtid.len(), 255);
        assert_eq!(pck.pgu.len(), 255);
        assert_eq!(pck.pgpdiff.len(), 255);
    }
    // A packet without reference indices reports none.
    pck.depacketize(&Bytes::from_static(&[0x00, 0xaa]))?;
    assert!(pck.pdiff.is_empty());
    Ok(())
}

/// A VP9 key frame header: frame_marker 2, profile 0, show_existing_frame 0,
/// frame_type 0 (key), show_frame 1, error_resilient_mode 0, the sync code,
/// color_space 1 (BT.601), color_range 0, then width-1 = 639 and
/// height-1 = 479 (16 bits each), then frame data.
pub(super) fn vp9_key_frame_640x480() -> Vec<u8> {
    // Bits: 10 0 0 0 0 1 0 | 0x49 0x83 0x42 | 001 0 | 0x027F | 0x01DF | pad
    let mut bits: Vec<u8> = vec![1, 0, 0, 0, 0, 0, 1, 0];
    for byte in [0x49u8, 0x83, 0x42] {
        for i in (0..8).rev() {
            bits.push((byte >> i) & 1);
        }
    }
    bits.extend([0, 0, 1, 0]);
    for value in [639u16, 479] {
        for i in (0..16).rev() {
            bits.push(((value >> i) & 1) as u8);
        }
    }
    while !bits.len().is_multiple_of(8) {
        bits.push(0);
    }
    let mut out: Vec<u8> = bits
        .chunks(8)
        .map(|c| c.iter().fold(0u8, |acc, b| (acc << 1) | b))
        .collect();
    out.extend([0xaa, 0xbb, 0xcc]);
    out
}

#[test]
fn test_vp9_frame_header_parse() {
    let header = Vp9FrameHeader::parse(&vp9_key_frame_640x480()).unwrap();
    assert_eq!(
        header,
        Vp9FrameHeader {
            key_frame: true,
            size: Some((640, 480)),
            ..Default::default()
        }
    );
    // An inter frame: frame_type 1. The header ends before the reference fields.
    let inter = Vp9FrameHeader::parse(&[0x86, 0x00]).unwrap();
    assert!(!inter.key_frame && !inter.intra_only);
    assert_eq!(inter.ref_frame_idx, None);
    // A whole inter frame header: refresh_frame_flags 0x04, references to slots 1, 2 and 3.
    let inter = Vp9FrameHeader::parse(&[0x86, 0x01, 0x09, 0x18]).unwrap();
    assert_eq!(inter.refresh_frame_flags, Some(0x04));
    assert_eq!(inter.ref_frame_idx, Some([1, 2, 3]));
    // Not VP9: frame_marker isn't 2.
    assert!(Vp9FrameHeader::parse(&[0x01, 0x02]).is_none());
}

/// Firefox decodes only non-flexible VP9 with the scalability structure on
/// key frames; the payloader used to send flexible mode with P=0 and no SS.
#[test]
fn test_vp9_payloader_non_flexible_mode() -> Result<()> {
    let mut pck = Vp9Payloader {
        initial_picture_id_fn: Some(Arc::new(|| -> u16 { 8692 })),
        ..Default::default()
    };
    let key = Bytes::from(vp9_key_frame_640x480());
    let out = pck.payload(100, &key)?;
    assert_eq!(out.len(), 1);
    // I=1 B=1 E=1 V=1 Z=1, P=0, F=0; picture id 8692 (M=1).
    assert_eq!(out[0][0], 0x8F);
    assert_eq!(
        &out[0][1..3],
        &[(8692u16 >> 8) as u8 | 0x80, (8692 & 0xFF) as u8]
    );
    // SS: N_S=0 Y=1 G=1, 640x480, N_G=1, T=0 U=1 R=1, P_DIFF=1.
    assert_eq!(
        &out[0][3..11],
        &[0x18, 0x02, 0x80, 0x01, 0xE0, 0x01, 0x14, 0x01]
    );
    assert_eq!(&out[0][11..], &key[..]);
    let mut depacketizer = Vp9Packet::default();
    assert_eq!(depacketizer.depacketize(&out[0])?, key);
    assert!(!depacketizer.f && !depacketizer.p && depacketizer.v);
    assert_eq!(depacketizer.width, vec![640]);
    assert_eq!(depacketizer.height, vec![480]);

    // An inter frame across two packets: P=1, no SS; B on the first, E on the
    // last; the next picture id.
    let inter = Bytes::from_static(&[0x86, 0x01, 0x02, 0x03]);
    let out = pck.payload(5, &inter)?;
    assert_eq!(out.len(), 2);
    assert_eq!(out[0][0], 0xC9); // I P B Z
    assert_eq!(out[1][0], 0xC5); // I P E Z
    assert_eq!(
        &out[0][1..3],
        &[(8693u16 >> 8) as u8 | 0x80, (8693 & 0xFF) as u8]
    );
    assert_eq!(&out[0][3..], &[0x86, 0x01]);
    assert_eq!(&out[1][3..], &[0x02, 0x03]);

    // flexible_mode keeps the old format.
    let mut flexible = Vp9Payloader {
        initial_picture_id_fn: Some(Arc::new(|| -> u16 { 8692 })),
        flexible_mode: true,
        ..Default::default()
    };
    let out = flexible.payload(100, &key)?;
    assert_eq!(out[0][0], 0x9C);
    assert_eq!(&out[0][3..], &key[..]);
    Ok(())
}