rtc-rtp 0.20.0

RTC RTP in Rust
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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
//! The RTP header and its extensions.
//!
//! [`Header`](crate::header::Header) is the fixed 12-byte header plus the optional CSRC list and header-extension
//! block. The `*_SHIFT`/`*_MASK` constants describe how the flag fields pack into the first two
//! octets, and the `*_OFFSET`/`*_LENGTH` constants give the byte positions a caller can patch in
//! place without re-encoding.
//!
//! Header extensions ([RFC 8285]) come in two forms, selected by
//! [`Header::extension_profile`](crate::header::Header::extension_profile): one-byte ids ([`EXTENSION_PROFILE_ONE_BYTE`](crate::header::EXTENSION_PROFILE_ONE_BYTE)) or two-byte ids
//! ([`EXTENSION_PROFILE_TWO_BYTE`](crate::header::EXTENSION_PROFILE_TWO_BYTE)) when an id above 14 is needed. Use
//! [`Header::set_extension`](crate::header::Header::set_extension) and [`Header::get_extension`](crate::header::Header::get_extension) rather than touching
//! [`Header::extensions`](crate::header::Header::extensions) directly — they keep [`Header::extensions_padding`](crate::header::Header::extensions_padding) and the extension
//! flag consistent, which marshalling depends on.
//!
//! [RFC 8285]: https://datatracker.ietf.org/doc/html/rfc8285

use shared::{
    error::{Error, Result},
    marshal::{Marshal, MarshalSize, Unmarshal},
};

use bytes::{Buf, BufMut, Bytes};

/// The length of the extension-profile and length fields that precede header extensions.
pub const HEADER_LENGTH: usize = 4;
/// Bit offset of the version field in the first header octet.
pub const VERSION_SHIFT: u8 = 6;
/// Bit mask of the version field once shifted.
pub const VERSION_MASK: u8 = 0x3;
/// Bit offset of the padding flag.
pub const PADDING_SHIFT: u8 = 5;
/// Bit mask of the padding flag once shifted.
pub const PADDING_MASK: u8 = 0x1;
/// Bit offset of the extension flag.
pub const EXTENSION_SHIFT: u8 = 4;
/// Bit mask of the extension flag once shifted.
pub const EXTENSION_MASK: u8 = 0x1;
/// Extension profile `0xBEDE`, which selects one-byte header extension ids ([RFC 8285]).
pub const EXTENSION_PROFILE_ONE_BYTE: u16 = 0xBEDE;
/// Extension profile `0x1000`, which selects two-byte header extension ids, allowing ids
/// above 14.
pub const EXTENSION_PROFILE_TWO_BYTE: u16 = 0x1000;
/// Extension id 15, reserved by the RFC and never assigned.
pub const EXTENSION_ID_RESERVED: u8 = 0xF;
/// Bit mask of the CSRC count field.
pub const CC_MASK: u8 = 0xF;
/// Bit offset of the marker bit.
pub const MARKER_SHIFT: u8 = 7;
/// Bit mask of the marker bit once shifted.
pub const MARKER_MASK: u8 = 0x1;
/// Bit mask of the payload-type field.
pub const PT_MASK: u8 = 0x7F;
/// Byte offset of the sequence number within the header.
pub const SEQ_NUM_OFFSET: usize = 2;
/// Length of the sequence number in bytes.
pub const SEQ_NUM_LENGTH: usize = 2;
/// Byte offset of the timestamp within the header.
pub const TIMESTAMP_OFFSET: usize = 4;
/// Length of the timestamp in bytes.
pub const TIMESTAMP_LENGTH: usize = 4;
/// Byte offset of the SSRC within the header.
pub const SSRC_OFFSET: usize = 8;
/// Length of the SSRC in bytes.
pub const SSRC_LENGTH: usize = 4;
/// Byte offset of the first CSRC within the header.
pub const CSRC_OFFSET: usize = 12;
/// Length of each CSRC in bytes.
pub const CSRC_LENGTH: usize = 4;

#[derive(Debug, Eq, PartialEq, Default, Clone)]
/// One RTP header extension: an id and its payload bytes.
pub struct Extension {
    /// The extension id, as negotiated by `a=extmap`.
    pub id: u8,
    /// The extension's value.
    pub payload: Bytes,
}

/// Header represents an RTP packet header
/// NOTE: PayloadOffset is populated by Marshal/Unmarshal and should not be modified
#[derive(Debug, Eq, PartialEq, Default, Clone)]
pub struct Header {
    /// The RTP version, always 2.
    pub version: u8,
    /// Whether the payload is followed by padding octets, the last giving the padding length.
    pub padding: bool,
    /// Whether a header-extension block follows the fixed header.
    pub extension: bool,
    /// The marker bit: the last packet of a video frame, or the start of a talk spurt for audio.
    pub marker: bool,
    /// The payload type, which identifies the codec as negotiated in SDP.
    pub payload_type: u8,
    /// Increments by one per packet sent; used to detect loss and restore order.
    pub sequence_number: u16,
    /// The sampling instant of the first octet, in the codec's clock rate.
    pub timestamp: u32,
    /// The synchronization source — the identifier of the stream this packet belongs to.
    pub ssrc: u32,
    /// The contributing sources, listed when a mixer combined several streams.
    pub csrc: Vec<u32>,
    /// Which header-extension form is in use: [`EXTENSION_PROFILE_ONE_BYTE`] or
    /// [`EXTENSION_PROFILE_TWO_BYTE`].
    pub extension_profile: u16,
    /// The header extensions present on this packet.
    pub extensions: Vec<Extension>,
    /// Padding bytes appended to the extension block so it ends on a 32-bit boundary.
    pub extensions_padding: usize,
}

impl Unmarshal for Header {
    /// Unmarshal parses the passed byte slice and stores the result in the Header this method is called upon
    fn unmarshal<B>(raw_packet: &mut B) -> Result<Self>
    where
        Self: Sized,
        B: Buf,
    {
        let raw_packet_len = raw_packet.remaining();
        if raw_packet_len < HEADER_LENGTH {
            return Err(Error::ErrHeaderSizeInsufficient);
        }
        /*
         *  0                   1                   2                   3
         *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
         * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
         * |V=2|P|X|  CC   |M|     PT      |       sequence number         |
         * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
         * |                           timestamp                           |
         * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
         * |           synchronization source (SSRC) identifier            |
         * +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
         * |            contributing source (CSRC) identifiers             |
         * |                             ....                              |
         * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
         */
        let b0 = raw_packet.get_u8();
        let version = b0 >> VERSION_SHIFT & VERSION_MASK;
        let padding = (b0 >> PADDING_SHIFT & PADDING_MASK) > 0;
        let extension = (b0 >> EXTENSION_SHIFT & EXTENSION_MASK) > 0;
        let cc = (b0 & CC_MASK) as usize;

        let mut curr_offset = CSRC_OFFSET + (cc * CSRC_LENGTH);
        if raw_packet_len < curr_offset {
            return Err(Error::ErrHeaderSizeInsufficient);
        }

        let b1 = raw_packet.get_u8();
        let marker = (b1 >> MARKER_SHIFT & MARKER_MASK) > 0;
        let payload_type = b1 & PT_MASK;

        let sequence_number = raw_packet.get_u16();
        let timestamp = raw_packet.get_u32();
        let ssrc = raw_packet.get_u32();

        let mut csrc = Vec::with_capacity(cc);
        for _ in 0..cc {
            csrc.push(raw_packet.get_u32());
        }
        let mut extensions_padding: usize = 0;
        let (extension_profile, extensions) = if extension {
            let expected = curr_offset + 4;
            if raw_packet_len < expected {
                return Err(Error::ErrHeaderSizeInsufficientForExtension);
            }
            let extension_profile = raw_packet.get_u16();
            curr_offset += 2;
            let extension_length = raw_packet.get_u16() as usize * 4;
            curr_offset += 2;

            let expected = curr_offset + extension_length;
            if raw_packet_len < expected {
                return Err(Error::ErrHeaderSizeInsufficientForExtension);
            }

            let mut extensions = vec![];
            match extension_profile {
                // RFC 8285 RTP One Byte Header Extension
                EXTENSION_PROFILE_ONE_BYTE => {
                    let end = curr_offset + extension_length;
                    while curr_offset < end {
                        let b = raw_packet.get_u8();
                        if b == 0x00 {
                            // padding
                            curr_offset += 1;
                            extensions_padding += 1;
                            continue;
                        }

                        let extid = b >> 4;
                        let len = ((b & (0xFF ^ 0xF0)) + 1) as usize;
                        curr_offset += 1;

                        if extid == EXTENSION_ID_RESERVED {
                            break;
                        }

                        if len > raw_packet.remaining() {
                            return Err(Error::ErrHeaderSizeInsufficientForExtension);
                        }

                        extensions.push(Extension {
                            id: extid,
                            payload: raw_packet.copy_to_bytes(len),
                        });
                        curr_offset += len;
                    }
                }
                // RFC 8285 RTP Two Byte Header Extension
                EXTENSION_PROFILE_TWO_BYTE => {
                    let end = curr_offset + extension_length;
                    while curr_offset < end {
                        let b = raw_packet.get_u8();
                        if b == 0x00 {
                            // padding
                            curr_offset += 1;
                            extensions_padding += 1;
                            continue;
                        }

                        let extid = b;
                        curr_offset += 1;

                        if curr_offset >= end {
                            return Err(Error::ErrHeaderSizeInsufficientForExtension);
                        }

                        let len = raw_packet.get_u8() as usize;
                        curr_offset += 1;

                        if len > raw_packet.remaining() {
                            return Err(Error::ErrHeaderSizeInsufficientForExtension);
                        }

                        extensions.push(Extension {
                            id: extid,
                            payload: raw_packet.copy_to_bytes(len),
                        });
                        curr_offset += len;
                    }
                }
                // RFC3550 Extension
                _ => {
                    if raw_packet_len < curr_offset + extension_length {
                        return Err(Error::ErrHeaderSizeInsufficientForExtension);
                    }
                    extensions.push(Extension {
                        id: 0,
                        payload: raw_packet.copy_to_bytes(extension_length),
                    });
                }
            };

            (extension_profile, extensions)
        } else {
            (0, vec![])
        };

        Ok(Header {
            version,
            padding,
            extension,
            marker,
            payload_type,
            sequence_number,
            timestamp,
            ssrc,
            csrc,
            extension_profile,
            extensions,
            extensions_padding,
        })
    }
}

impl Header {
    /// Marshaled header size given an already-computed extension payload length
    /// (see [`Header::get_extension_payload_len`]). Lets `marshal_to` size the
    /// buffer and write the extension length field from a single scan of the
    /// extensions instead of walking them via `marshal_size` and again directly.
    fn marshal_size_for(&self, extension_payload_len: usize) -> usize {
        let mut head_size = 12 + (self.csrc.len() * CSRC_LENGTH);
        if self.extension {
            let padded = extension_payload_len + self.extensions_padding;
            head_size += 4 + padded.div_ceil(4) * 4;
        }
        head_size
    }
}

impl MarshalSize for Header {
    /// MarshalSize returns the size of the packet once marshaled.
    fn marshal_size(&self) -> usize {
        let extension_payload_len = if self.extension {
            self.get_extension_payload_len()
        } else {
            0
        };
        self.marshal_size_for(extension_payload_len)
    }
}

impl Marshal for Header {
    /// Marshal serializes the header and writes to the buffer.
    fn marshal_to(&self, mut buf: &mut [u8]) -> Result<usize> {
        /*
         *  0                   1                   2                   3
         *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
         * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
         * |V=2|P|X|  CC   |M|     PT      |       sequence number         |
         * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
         * |                           timestamp                           |
         * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
         * |           synchronization source (SSRC) identifier            |
         * +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
         * |            contributing source (CSRC) identifiers             |
         * |                             ....                              |
         * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
         */
        let remaining_before = buf.remaining_mut();
        // Scan the extensions once here; reused for the bounds check, the
        // extension length field, and the trailing padding below (previously
        // walked three times: marshal_size() here plus twice in the body).
        let extension_payload_len = if self.extension {
            self.get_extension_payload_len()
        } else {
            0
        };
        if remaining_before < self.marshal_size_for(extension_payload_len) {
            return Err(Error::ErrBufferTooSmall);
        }

        // The first byte contains the version, padding bit, extension bit, and csrc size
        let mut b0 = (self.version << VERSION_SHIFT) | self.csrc.len() as u8;
        if self.padding {
            b0 |= 1 << PADDING_SHIFT;
        }

        if self.extension {
            b0 |= 1 << EXTENSION_SHIFT;
        }
        buf.put_u8(b0);

        // The second byte contains the marker bit and payload type.
        let mut b1 = self.payload_type;
        if self.marker {
            b1 |= 1 << MARKER_SHIFT;
        }
        buf.put_u8(b1);

        buf.put_u16(self.sequence_number);
        buf.put_u32(self.timestamp);
        buf.put_u32(self.ssrc);

        for csrc in &self.csrc {
            buf.put_u32(*csrc);
        }

        if self.extension {
            buf.put_u16(self.extension_profile);

            // extension_payload_len computed once at the top of this function.
            if self.extension_profile != EXTENSION_PROFILE_ONE_BYTE
                && self.extension_profile != EXTENSION_PROFILE_TWO_BYTE
                && !extension_payload_len.is_multiple_of(4)
            {
                //the payload must be in 32-bit words.
                return Err(Error::HeaderExtensionPayloadNot32BitWords);
            }
            let extension_payload_size = (extension_payload_len as u16).div_ceil(4);
            buf.put_u16(extension_payload_size);

            match self.extension_profile {
                // RFC 8285 RTP One Byte Header Extension
                EXTENSION_PROFILE_ONE_BYTE => {
                    for extension in &self.extensions {
                        buf.put_u8((extension.id << 4) | (extension.payload.len() as u8 - 1));
                        buf.put(&*extension.payload);
                    }
                }
                // RFC 8285 RTP Two Byte Header Extension
                EXTENSION_PROFILE_TWO_BYTE => {
                    for extension in &self.extensions {
                        buf.put_u8(extension.id);
                        buf.put_u8(extension.payload.len() as u8);
                        buf.put(&*extension.payload);
                    }
                }
                // RFC3550 Extension
                _ => {
                    if self.extensions.len() != 1 {
                        return Err(Error::ErrRfc3550headerIdrange);
                    }

                    if let Some(extension) = self.extensions.first() {
                        let ext_len = extension.payload.len();
                        if ext_len % 4 != 0 {
                            return Err(Error::HeaderExtensionPayloadNot32BitWords);
                        }
                        buf.put(&*extension.payload);
                    }
                }
            };

            // add padding to reach 4 bytes boundaries
            for _ in extension_payload_len..extension_payload_size as usize * 4 {
                buf.put_u8(0);
            }
        }

        let remaining_after = buf.remaining_mut();
        Ok(remaining_before - remaining_after)
    }
}

impl Header {
    /// The total encoded length of the extension payloads, padding excluded.
    pub fn get_extension_payload_len(&self) -> usize {
        let payload_len: usize = self
            .extensions
            .iter()
            .map(|extension| extension.payload.len())
            .sum();

        let profile_len = self.extensions.len()
            * match self.extension_profile {
                EXTENSION_PROFILE_ONE_BYTE => 1,
                EXTENSION_PROFILE_TWO_BYTE => 2,
                _ => 0,
            };

        payload_len + profile_len
    }

    /// SetExtension sets an RTP header extension
    pub fn set_extension(&mut self, id: u8, payload: Bytes) -> Result<()> {
        let payload_len = payload.len() as isize;
        if self.extension {
            let extension_profile_len = match self.extension_profile {
                EXTENSION_PROFILE_ONE_BYTE => {
                    if !(1..=14).contains(&id) {
                        return Err(Error::ErrRfc8285oneByteHeaderIdrange);
                    }
                    if payload_len > 16 {
                        return Err(Error::ErrRfc8285oneByteHeaderSize);
                    }
                    1
                }
                EXTENSION_PROFILE_TWO_BYTE => {
                    if id < 1 {
                        return Err(Error::ErrRfc8285twoByteHeaderIdrange);
                    }
                    if payload_len > 255 {
                        return Err(Error::ErrRfc8285twoByteHeaderSize);
                    }
                    2
                }
                _ => {
                    if id != 0 {
                        return Err(Error::ErrRfc3550headerIdrange);
                    }
                    0
                }
            };

            let delta;
            // Update existing if it exists else add new extension
            if let Some(extension) = self
                .extensions
                .iter_mut()
                .find(|extension| extension.id == id)
            {
                delta = payload_len - extension.payload.len() as isize;
                extension.payload = payload;
            } else {
                delta = payload_len + extension_profile_len;
                self.extensions.push(Extension { id, payload });
            }

            match delta.cmp(&0) {
                std::cmp::Ordering::Less => {
                    self.extensions_padding =
                        ((self.extensions_padding as isize - delta) % 4) as usize;
                }
                std::cmp::Ordering::Greater => {
                    let extension_padding = (delta % 4) as usize;
                    if self.extensions_padding < extension_padding {
                        self.extensions_padding = (self.extensions_padding + 4) - extension_padding;
                    } else {
                        self.extensions_padding -= extension_padding
                    }
                }
                _ => {}
            }
        } else {
            // No existing header extensions
            self.extension = true;
            let mut extension_profile_len = 0;
            self.extension_profile = match payload_len {
                0..=16 => {
                    extension_profile_len = 1;
                    EXTENSION_PROFILE_ONE_BYTE
                }
                17..=255 => {
                    extension_profile_len = 2;
                    EXTENSION_PROFILE_TWO_BYTE
                }
                _ => self.extension_profile,
            };

            let extension_padding = (payload.len() + extension_profile_len) % 4;
            if self.extensions_padding < extension_padding {
                self.extensions_padding = self.extensions_padding + 4 - extension_padding;
            } else {
                self.extensions_padding -= extension_padding
            }
            self.extensions.push(Extension { id, payload });
        }
        Ok(())
    }

    /// returns an extension id array
    pub fn get_extension_ids(&self) -> Vec<u8> {
        if self.extension {
            self.extensions.iter().map(|e| e.id).collect()
        } else {
            vec![]
        }
    }

    /// returns an RTP header extension
    pub fn get_extension(&self, id: u8) -> Option<Bytes> {
        if self.extension {
            self.extensions
                .iter()
                .find(|extension| extension.id == id)
                .map(|extension| extension.payload.clone())
        } else {
            None
        }
    }

    /// Removes an RTP Header extension
    pub fn del_extension(&mut self, id: u8) -> Result<()> {
        if self.extension {
            if let Some(index) = self
                .extensions
                .iter()
                .position(|extension| extension.id == id)
            {
                let extension = self.extensions.remove(index);

                let extension_profile_len = match self.extension_profile {
                    EXTENSION_PROFILE_ONE_BYTE => 1,
                    EXTENSION_PROFILE_TWO_BYTE => 2,
                    _ => 0,
                };

                let extension_padding = (extension.payload.len() + extension_profile_len) % 4;
                self.extensions_padding = (self.extensions_padding + extension_padding) % 4;

                Ok(())
            } else {
                Err(Error::ErrHeaderExtensionNotFound)
            }
        } else {
            Err(Error::ErrHeaderExtensionsNotEnabled)
        }
    }
}