msf-rtp 0.4.1

Real-time Transport Protocol (RTP) for 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
//! RTCP types.

mod bye;
mod channel;
mod context;
mod handler;
mod report;
mod sdes;
mod stats;

use std::ops::Deref;

use bytes::{Buf, Bytes, BytesMut};
use zerocopy::{
    byteorder::network_endian::U16, FromBytes, Immutable, IntoBytes, KnownLayout, SizeError,
    Unaligned,
};

use crate::InvalidInput;

pub use self::{
    bye::ByePacket,
    channel::RtcpChannel,
    context::{RtcpContext, RtcpContextHandle},
    handler::{MuxedRtcpHandler, RtcpHandler, RtcpHandlerOptions},
    report::{ReceiverReport, ReportBlock, SenderReport},
    sdes::{SourceDescription, SourceDescriptionPacket},
};

/// Compound RTCP packet.
#[derive(Clone)]
pub struct CompoundRtcpPacket {
    inner: Vec<RtcpPacket>,
}

impl CompoundRtcpPacket {
    /// Create a new compound packet.
    pub fn new<T>(packets: T) -> Self
    where
        T: Into<Vec<RtcpPacket>>,
    {
        Self {
            inner: packets.into(),
        }
    }

    /// Decode a compound RTCP packet.
    pub fn decode(mut frame: Bytes) -> Result<Self, InvalidInput> {
        let mut res = Vec::new();

        while !frame.is_empty() {
            res.push(RtcpPacket::decode(&mut frame)?);
        }

        Ok(res.into())
    }

    /// Encode the packet.
    pub fn encode(&self, buf: &mut BytesMut) {
        buf.reserve(self.raw_size());

        for packet in &self.inner {
            packet.encode(buf);
        }
    }

    /// Get encoded size of the compound packet.
    pub fn raw_size(&self) -> usize {
        self.inner.iter().map(|packet| packet.length()).sum()
    }
}

impl Deref for CompoundRtcpPacket {
    type Target = [RtcpPacket];

    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl From<RtcpPacket> for CompoundRtcpPacket {
    #[inline]
    fn from(packet: RtcpPacket) -> Self {
        Self {
            inner: vec![packet],
        }
    }
}

impl<T> From<T> for CompoundRtcpPacket
where
    T: Into<Vec<RtcpPacket>>,
{
    #[inline]
    fn from(packets: T) -> Self {
        Self::new(packets)
    }
}

/// RTCP packet type.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum RtcpPacketType {
    SR,
    RR,
    SDES,
    BYE,
    Other(u8),
}

impl RtcpPacketType {
    /// Get type ID.
    #[inline]
    pub fn raw_id(self) -> u8 {
        match self {
            RtcpPacketType::SR => 200,
            RtcpPacketType::RR => 201,
            RtcpPacketType::SDES => 202,
            RtcpPacketType::BYE => 203,
            RtcpPacketType::Other(id) => id,
        }
    }
}

impl From<u8> for RtcpPacketType {
    #[inline]
    fn from(id: u8) -> RtcpPacketType {
        match id {
            200 => RtcpPacketType::SR,
            201 => RtcpPacketType::RR,
            202 => RtcpPacketType::SDES,
            203 => RtcpPacketType::BYE,
            id => RtcpPacketType::Other(id),
        }
    }
}

/// Helper struct.
#[derive(Copy, Clone, KnownLayout, Immutable, Unaligned, IntoBytes, FromBytes)]
#[repr(C)]
struct RawRtcpHeader {
    options: u8,
    packet_type: u8,
    length: U16,
}

/// RTCP header.
#[derive(Copy, Clone)]
pub struct RtcpHeader {
    options: u8,
    packet_type: RtcpPacketType,
    length: u16,
}

impl RtcpHeader {
    /// Size of an encoded RTCP header.
    pub const RAW_SIZE: usize = std::mem::size_of::<RawRtcpHeader>();

    /// Create a new packet header.
    #[inline]
    pub const fn new(packet_type: RtcpPacketType) -> Self {
        Self {
            options: 2 << 6,
            packet_type,
            length: 0,
        }
    }

    /// Decode an RTCP header.
    pub fn decode(data: &mut Bytes) -> Result<Self, InvalidInput> {
        let (raw, _) = RawRtcpHeader::ref_from_prefix(data)
            .map_err(SizeError::from)
            .map_err(|_| InvalidInput::new())?;

        if (raw.options >> 6) != 2 {
            return Err(InvalidInput::new());
        }

        let res = Self {
            options: raw.options,
            packet_type: raw.packet_type.into(),
            length: raw.length.get(),
        };

        data.advance(std::mem::size_of::<RawRtcpHeader>());

        Ok(res)
    }

    /// Encode the header.
    pub fn encode(&self, buf: &mut BytesMut) {
        let raw = RawRtcpHeader {
            options: self.options,
            packet_type: self.packet_type.raw_id(),
            length: U16::new(self.length),
        };

        buf.extend_from_slice(raw.as_bytes());
    }

    /// Check if the padding bit is set.
    #[inline]
    pub fn padding(&self) -> bool {
        (self.options & 0x20) != 0
    }

    /// Set the padding bit.
    #[inline]
    pub fn with_padding(mut self, padding: bool) -> Self {
        self.options &= !0x20;
        self.options |= (padding as u8) << 5;
        self
    }

    /// Get packet length in bytes.
    #[inline]
    pub fn packet_length(&self) -> usize {
        ((self.length as usize) + 1) << 2
    }

    /// Set the packet length in bytes.
    ///
    /// Please note that the packet length must be a multiple of four and it
    /// must be from the range `4..=262_144`.
    ///
    /// # Panics
    /// The method panics if the constraints on the packet length mentioned
    /// above are not met.
    #[inline]
    pub fn with_packet_length(mut self, length: usize) -> Self {
        assert!((4..=262_144).contains(&length) && (length & 3) == 0);

        self.length = ((length >> 2) - 1) as u16;
        self
    }

    /// Get RTCP packet type.
    #[inline]
    pub fn packet_type(&self) -> RtcpPacketType {
        self.packet_type
    }

    /// Set RTCP packet type.
    #[inline]
    pub fn with_packet_type(mut self, packet_type: RtcpPacketType) -> Self {
        self.packet_type = packet_type;
        self
    }

    /// Get number of items in the packet body.
    ///
    /// Note: Only the lower 5 bits are actually used.
    #[inline]
    pub fn item_count(&self) -> u8 {
        self.options & 0x1f
    }

    /// Set the number of items in the packet body.
    ///
    /// # Panics
    /// The method panics if the number of items is greater than 31.
    #[inline]
    pub fn with_item_count(mut self, count: u8) -> Self {
        assert!(count < 32);

        self.options &= !0x1f;
        self.options |= count & 0x1f;
        self
    }

    /// Get encoded size of the header.
    #[inline]
    pub fn raw_size(&self) -> usize {
        std::mem::size_of::<RawRtcpHeader>()
    }
}

/// RTCP packet.
#[derive(Clone)]
pub struct RtcpPacket {
    header: RtcpHeader,
    payload: Bytes,
}

impl RtcpPacket {
    /// Create a new packet.
    #[inline]
    pub const fn new(packet_type: RtcpPacketType) -> Self {
        Self {
            header: RtcpHeader::new(packet_type),
            payload: Bytes::new(),
        }
    }

    /// Create a new RTCP packet from given parts.
    pub fn from_parts(header: RtcpHeader, payload: Bytes) -> Result<Self, InvalidInput> {
        if header.padding() {
            let padding_len = payload.last().copied().ok_or_else(InvalidInput::new)? as usize;

            if padding_len == 0 || payload.len() < padding_len {
                return Err(InvalidInput::new());
            }
        }

        let packet_len = header.packet_length();

        if packet_len != (payload.len() + 4) {
            return Err(InvalidInput::new());
        }

        let res = Self { header, payload };

        Ok(res)
    }

    /// Deconstruct the packet into its header and payload.
    #[inline]
    pub fn deconstruct(self) -> (RtcpHeader, Bytes) {
        (self.header, self.payload)
    }

    /// Decode an RTCP packet.
    pub fn decode(data: &mut Bytes) -> Result<Self, InvalidInput> {
        let mut buffer = data.clone();

        let header = RtcpHeader::decode(&mut buffer)?;

        let payload_len = header.packet_length() - 4;

        if buffer.len() < payload_len {
            return Err(InvalidInput::new());
        }

        let res = Self::from_parts(header, buffer.split_to(payload_len))?;

        *data = buffer;

        Ok(res)
    }

    /// Encode the packet.
    pub fn encode(&self, buf: &mut BytesMut) {
        buf.reserve(self.header.packet_length());

        self.header.encode(buf);

        buf.extend_from_slice(&self.payload);
    }

    /// Get the packet header.
    #[inline]
    pub fn header(&self) -> &RtcpHeader {
        &self.header
    }

    /// Get the packet type.
    #[inline]
    pub fn packet_type(&self) -> RtcpPacketType {
        self.header.packet_type()
    }

    /// Set the packet type.
    #[inline]
    pub fn with_packet_type(mut self, packet_type: RtcpPacketType) -> Self {
        self.header = self.header.with_packet_type(packet_type);
        self
    }

    /// Get number of items in the packet body.
    ///
    /// Note: Only the lower 5 bits are actually used.
    #[inline]
    pub fn item_count(&self) -> u8 {
        self.header.item_count()
    }

    /// Set the number of items in the packet body.
    ///
    /// # Panics
    /// The method panics if the number of items is greater than 31.
    #[inline]
    pub fn with_item_count(mut self, count: u8) -> Self {
        self.header = self.header.with_item_count(count);
        self
    }

    /// Get packet length in bytes.
    #[inline]
    pub fn length(&self) -> usize {
        self.header.packet_length()
    }

    /// Get length of the optional padding.
    ///
    /// Zero means that the padding is not used at all.
    #[inline]
    pub fn padding(&self) -> u8 {
        if self.header.padding() {
            *self.payload.last().unwrap()
        } else {
            0
        }
    }

    /// Get the packet payload including the optional padding.
    #[inline]
    pub fn payload(&self) -> &Bytes {
        &self.payload
    }

    /// Get the packet payload without any padding.
    #[inline]
    pub fn stripped_payload(&self) -> Bytes {
        let payload_len = self.payload.len();
        let padding_len = self.padding() as usize;

        let len = payload_len - padding_len;

        self.payload.slice(..len)
    }

    /// Set the payload and add padding of a given length.
    ///
    /// If the padding is zero, no padding will be added and the padding bit in
    /// the RTP header will be set to zero.
    ///
    /// # Panics
    /// The method panics if the payload length including padding is not a
    /// multiple of four or if the payload length including padding is greater
    /// than 262_140.
    pub fn with_payload(mut self, mut payload: Bytes, padding: u8) -> Self {
        if padding > 0 {
            let len = payload.len() + (padding as usize);

            let mut buffer = BytesMut::with_capacity(len);

            buffer.extend_from_slice(&payload);
            buffer.resize(len, 0);

            buffer[len - 1] = padding;

            payload = buffer.freeze();

            self.header = self
                .header
                .with_padding(true)
                .with_packet_length(4 + payload.len());
        } else {
            self.header = self
                .header
                .with_padding(false)
                .with_packet_length(4 + payload.len());
        }

        self.payload = payload;

        self
    }

    /// Set the payload that already includes padding.
    ///
    /// # Panics
    /// The method panics if the following conditions are not met:
    /// * The payload must not be empty.
    /// * The last byte of the payload (i.e. the length of the padding) must
    ///   not be zero.
    /// * The length of the padding must not be greater than the length of the
    ///   payload itself.
    /// * The payload length including padding must be a multiple of four.
    /// * The payload length including padding must not be greater than
    ///   262_140.
    pub fn with_padded_payload(mut self, payload: Bytes) -> Self {
        let padding_len = payload.last().copied().expect("empty payload") as usize;

        assert!(padding_len > 0 && payload.len() >= padding_len);

        self.header = self
            .header
            .with_padding(true)
            .with_packet_length(payload.len());

        self.payload = payload;
        self
    }

    /// Get encoded size of the packet.
    #[inline]
    pub fn raw_size(&self) -> usize {
        self.length()
    }
}