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
492
493
494
495
496
497
use std::time::Duration;

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

use crate::{InvalidInput, RtcpPacket, RtcpPacketType};

/// Helper struct.
#[derive(Copy, Clone, KnownLayout, Immutable, Unaligned, IntoBytes, FromBytes)]
#[repr(C)]
struct RawReportBlock {
    ssrc: U32,
    loss: U32,
    extended_sequence_number: U32,
    jitter: U32,
    last_sr_timestamp: U32,
    delay_since_last_sr: U32,
}

/// Sender/receiver report block.
#[derive(Copy, Clone)]
pub struct ReportBlock {
    ssrc: u32,
    loss: u32,
    extended_sequence_number: u32,
    jitter: u32,
    last_sr_timestamp: u32,
    delay_since_last_sr: u32,
}

impl ReportBlock {
    /// Size of an encoded report block.
    pub const RAW_SIZE: usize = std::mem::size_of::<RawReportBlock>();

    /// Create a new report block.
    #[inline]
    pub const fn new(ssrc: u32) -> Self {
        Self {
            ssrc,
            loss: 0,
            extended_sequence_number: 0,
            jitter: 0,
            last_sr_timestamp: 0,
            delay_since_last_sr: 0,
        }
    }

    /// Decode a report block from given data.
    pub fn decode(data: &mut Bytes) -> Result<Self, InvalidInput> {
        let (raw, _) = RawReportBlock::ref_from_prefix(data)
            .map_err(SizeError::from)
            .map_err(|_| InvalidInput::new())?;

        let res = Self {
            ssrc: raw.ssrc.get(),
            loss: raw.loss.get(),
            extended_sequence_number: raw.extended_sequence_number.get(),
            jitter: raw.jitter.get(),
            last_sr_timestamp: raw.last_sr_timestamp.get(),
            delay_since_last_sr: raw.delay_since_last_sr.get(),
        };

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

        Ok(res)
    }

    /// Encode the report block.
    pub fn encode(&self, buf: &mut BytesMut) {
        let raw = RawReportBlock {
            ssrc: U32::new(self.ssrc),
            loss: U32::new(self.loss),
            extended_sequence_number: U32::new(self.extended_sequence_number),
            jitter: U32::new(self.jitter),
            last_sr_timestamp: U32::new(self.last_sr_timestamp),
            delay_since_last_sr: U32::new(self.delay_since_last_sr),
        };

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

    /// Get SSRC.
    #[inline]
    pub fn ssrc(&self) -> u32 {
        self.ssrc
    }

    /// Set SSRC.
    #[inline]
    pub fn with_ssrc(mut self, ssrc: u32) -> Self {
        self.ssrc = ssrc;
        self
    }

    /// Get fractional loss as 0.8 fixed point number.
    #[inline]
    pub fn fractional_loss(&self) -> u8 {
        (self.loss >> 24) as u8
    }

    /// Set fractional loss as 0.8 fixed point number.
    #[inline]
    pub fn with_fractional_loss(mut self, loss: u8) -> Self {
        self.loss &= 0x00ffffff;
        self.loss |= (loss as u32) << 24;
        self
    }

    /// Get cumulative packet loss (the precision is only up to 24 bits).
    #[inline]
    pub fn cumulative_loss(&self) -> i32 {
        ((self.loss << 8) as i32) >> 8
    }

    /// Set cumulative packet loss (the precision is only up to 24 bits).
    #[inline]
    pub fn with_cumulative_loss(mut self, loss: i32) -> Self {
        let min = -(1i32 << 23);
        let max = (1i32 << 23) - 1;

        let loss = loss.clamp(min, max) as u32;

        self.loss &= 0xff000000;
        self.loss |= loss & 0x00ffffff;
        self
    }

    /// Set loss calculated from a given number of expected packets vs. a given
    /// number of received packets.
    pub fn with_loss(self, expected: u64, received: u64) -> Self {
        let delta = expected as i64 - received as i64;

        let fraction = if delta < 0 {
            0
        } else {
            ((delta as u64) << 8) / expected
        };

        self.with_fractional_loss(fraction as u8)
            .with_cumulative_loss(delta as i32)
    }

    /// Get extended highest sequence number.
    #[inline]
    pub fn extended_sequence_number(&self) -> u32 {
        self.extended_sequence_number
    }

    /// Set the extended sequence number.
    #[inline]
    pub fn with_extended_sequence_number(mut self, n: u32) -> Self {
        self.extended_sequence_number = n;
        self
    }

    /// Get jitter.
    #[inline]
    pub fn jitter(&self) -> u32 {
        self.jitter
    }

    /// Set the jitter.
    #[inline]
    pub fn with_jitter(mut self, jitter: u32) -> Self {
        self.jitter = jitter;
        self
    }

    /// Get NTP timestamp of the last sender report (after truncating to the
    /// middle 32 bits).
    ///
    /// The returned timestamp is a 32.32 fixed point number.
    #[inline]
    pub fn last_sr_timestamp(&self) -> u64 {
        (self.last_sr_timestamp as u64) << 16
    }

    /// Set NTP timestamp of the last sender report.
    ///
    /// The timestamp is expected to be a 32.32 fixed point number and it will
    /// be truncated to the middle 32 bits.
    #[inline]
    pub fn with_last_sr_timestamp(mut self, ts: u64) -> Self {
        self.last_sr_timestamp = (ts >> 16) as u32;
        self
    }

    /// Get delay since the last sender report.
    #[inline]
    pub fn delay_since_last_sr(&self) -> Duration {
        let secs = (self.delay_since_last_sr >> 16) as u64;
        let nanos = ((self.delay_since_last_sr & 0xffff) as u64 * 1_000_000_000) >> 16;

        Duration::new(secs, nanos as u32)
    }

    /// Set delay since the last sender report.
    #[inline]
    pub fn with_delay_since_last_sr(mut self, delay: Duration) -> Self {
        let secs = (delay.as_secs() << 16) as u32;
        let fraction = (((delay.subsec_nanos() as u64) << 16) / 1_000_000_000) as u32;

        self.delay_since_last_sr = secs + fraction;
        self
    }

    /// Get size of the encoded report block.
    #[inline]
    pub fn raw_size(&self) -> usize {
        Self::RAW_SIZE
    }
}

/// Helper struct.
#[derive(Copy, Clone, KnownLayout, Immutable, Unaligned, IntoBytes, FromBytes)]
#[repr(C)]
struct RawSenderReportHeader {
    sender_ssrc: U32,
    ntp_timestamp: U64,
    rtp_timestamp: U32,
    packet_count: U32,
    octet_count: U32,
}

/// Sender report.
#[derive(Clone)]
pub struct SenderReport {
    sender_ssrc: u32,
    ntp_timestamp: u64,
    rtp_timestamp: u32,
    packet_count: u32,
    octet_count: u32,
    report_blocks: Vec<ReportBlock>,
}

impl SenderReport {
    /// Create a new sender report.
    #[inline]
    pub const fn new(sender_ssrc: u32) -> Self {
        Self {
            sender_ssrc,
            ntp_timestamp: 0,
            rtp_timestamp: 0,
            packet_count: 0,
            octet_count: 0,
            report_blocks: Vec::new(),
        }
    }

    /// Decode sender report.
    pub fn decode(packet: &RtcpPacket) -> Result<Self, InvalidInput> {
        let header = packet.header();

        let mut data = packet.stripped_payload();

        let (raw, _) = RawSenderReportHeader::ref_from_prefix(&data)
            .map_err(SizeError::from)
            .map_err(|_| InvalidInput::new())?;

        let mut res = Self {
            sender_ssrc: raw.sender_ssrc.get(),
            ntp_timestamp: raw.ntp_timestamp.get(),
            rtp_timestamp: raw.rtp_timestamp.get(),
            packet_count: raw.packet_count.get(),
            octet_count: raw.octet_count.get(),
            report_blocks: Vec::with_capacity(header.item_count() as usize),
        };

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

        for _ in 0..header.item_count() {
            res.report_blocks.push(ReportBlock::decode(&mut data)?);
        }

        Ok(res)
    }

    /// Encode the sender report.
    pub fn encode(&self) -> RtcpPacket {
        let mut payload = BytesMut::with_capacity(self.raw_size());

        let raw = RawSenderReportHeader {
            sender_ssrc: U32::new(self.sender_ssrc),
            ntp_timestamp: U64::new(self.ntp_timestamp),
            rtp_timestamp: U32::new(self.rtp_timestamp),
            packet_count: U32::new(self.packet_count),
            octet_count: U32::new(self.octet_count),
        };

        payload.extend_from_slice(raw.as_bytes());

        for block in &self.report_blocks {
            block.encode(&mut payload);
        }

        RtcpPacket::new(RtcpPacketType::SR)
            .with_item_count(self.report_blocks.len() as u8)
            .with_payload(payload.freeze(), 0)
    }

    /// Get SSRC identifier of the sender.
    #[inline]
    pub fn sender_ssrc(&self) -> u32 {
        self.sender_ssrc
    }

    /// Set the SSRC identifier of the sender.
    #[inline]
    pub fn with_sender_ssrc(mut self, ssrc: u32) -> Self {
        self.sender_ssrc = ssrc;
        self
    }

    /// Get NTP timestamp as a 32.32 fixed point number.
    #[inline]
    pub fn ntp_timestamp(&self) -> u64 {
        self.ntp_timestamp
    }

    /// Set the NTP timestamp as a 32.32. fixed point number.
    #[inline]
    pub fn with_ntp_timestamp(mut self, timestamp: u64) -> Self {
        self.ntp_timestamp = timestamp;
        self
    }

    /// Get RTP timestamp.
    #[inline]
    pub fn rtp_timestamp(&self) -> u32 {
        self.rtp_timestamp
    }

    /// Set the RTP timestamp.
    #[inline]
    pub fn with_rtp_timestamp(mut self, timestamp: u32) -> Self {
        self.rtp_timestamp = timestamp;
        self
    }

    /// Get packet count.
    #[inline]
    pub fn packet_count(&self) -> u32 {
        self.packet_count
    }

    /// Set the packet count.
    #[inline]
    pub fn with_packet_count(mut self, count: u32) -> Self {
        self.packet_count = count;
        self
    }

    /// Get octet count.
    #[inline]
    pub fn octet_count(&self) -> u32 {
        self.octet_count
    }

    /// Set the octet count.
    #[inline]
    pub fn with_octet_count(mut self, count: u32) -> Self {
        self.octet_count = count;
        self
    }

    /// Get report blocks.
    #[inline]
    pub fn report_blocks(&self) -> &[ReportBlock] {
        &self.report_blocks
    }

    /// Set the report blocks.
    ///
    /// # Panics
    /// The method will panic if the number of report blocks is greater than
    /// 31.
    #[inline]
    pub fn with_report_blocks<T>(mut self, blocks: T) -> Self
    where
        T: Into<Vec<ReportBlock>>,
    {
        let blocks = blocks.into();

        assert!(blocks.len() < 32);

        self.report_blocks = blocks;
        self
    }

    /// Get size of the encoded sender report.
    #[inline]
    pub fn raw_size(&self) -> usize {
        std::mem::size_of::<RawSenderReportHeader>()
            + std::mem::size_of::<RawReportBlock>() * self.report_blocks.len()
    }
}

/// Receiver report.
#[derive(Clone)]
pub struct ReceiverReport {
    sender_ssrc: u32,
    report_blocks: Vec<ReportBlock>,
}

impl ReceiverReport {
    /// Create a new receiver report.
    #[inline]
    pub const fn new(sender_ssrc: u32) -> Self {
        Self {
            sender_ssrc,
            report_blocks: Vec::new(),
        }
    }

    /// Decode receiver report.
    pub fn decode(packet: &RtcpPacket) -> Result<Self, InvalidInput> {
        let header = packet.header();

        let mut data = packet.stripped_payload();

        if data.len() < 4 {
            return Err(InvalidInput::new());
        }

        let mut res = Self {
            sender_ssrc: data.get_u32(),
            report_blocks: Vec::with_capacity(header.item_count() as usize),
        };

        for _ in 0..header.item_count() {
            res.report_blocks.push(ReportBlock::decode(&mut data)?);
        }

        Ok(res)
    }

    /// Encode the sender report.
    pub fn encode(&self) -> RtcpPacket {
        let mut payload = BytesMut::with_capacity(self.raw_size());

        payload.put_u32(self.sender_ssrc);

        for block in &self.report_blocks {
            block.encode(&mut payload);
        }

        RtcpPacket::new(RtcpPacketType::RR)
            .with_item_count(self.report_blocks.len() as u8)
            .with_payload(payload.freeze(), 0)
    }

    /// Get SSRC identifier of the sender.
    #[inline]
    pub fn sender_ssrc(&self) -> u32 {
        self.sender_ssrc
    }

    /// Set the SSRC identifier of the sender.
    #[inline]
    pub fn with_sender_ssrc(mut self, ssrc: u32) -> Self {
        self.sender_ssrc = ssrc;
        self
    }

    /// Get report blocks.
    #[inline]
    pub fn report_blocks(&self) -> &[ReportBlock] {
        &self.report_blocks
    }

    /// Set the report blocks.
    ///
    /// # Panics
    /// The method will panic if the number of report blocks is greater than
    /// 31.
    #[inline]
    pub fn with_report_blocks<T>(mut self, blocks: T) -> Self
    where
        T: Into<Vec<ReportBlock>>,
    {
        let blocks = blocks.into();

        assert!(blocks.len() < 32);

        self.report_blocks = blocks;
        self
    }

    /// Get size of the encoded sender report.
    #[inline]
    pub fn raw_size(&self) -> usize {
        4 + std::mem::size_of::<RawReportBlock>() * self.report_blocks.len()
    }
}