rtcp-types 0.1.0

RTCP packet parser and writers
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
// SPDX-License-Identifier: MIT OR Apache-2.0

use std::borrow::Borrow;

use crate::{
    prelude::*,
    utils::{pad_to_4bytes, parser, writer},
    RtcpPacket, RtcpPacketParser, RtcpParseError, RtcpWriteError,
};

pub mod fir;
pub mod nack;
pub mod pli;
pub mod rpsi;
pub mod sli;

/// The type of feedback packet.  There is currently transport and payload values supported for
/// feedback packets.
#[derive(Debug, Default, PartialEq, Eq)]
pub struct FciFeedbackPacketType {
    transport: bool,
    payload: bool,
}

impl FciFeedbackPacketType {
    pub const NONE: Self = Self {
        transport: false,
        payload: false,
    };
    pub const TRANSPORT: Self = Self {
        transport: true,
        payload: false,
    };
    pub const PAYLOAD: Self = Self {
        transport: false,
        payload: true,
    };
}

impl std::ops::BitOr<FciFeedbackPacketType> for FciFeedbackPacketType {
    type Output = Self;
    fn bitor(self, rhs: Self) -> Self::Output {
        Self {
            transport: self.transport | rhs.transport,
            payload: self.payload | rhs.payload,
        }
    }
}

impl std::ops::BitAnd<FciFeedbackPacketType> for FciFeedbackPacketType {
    type Output = Self;
    fn bitand(self, rhs: Self) -> Self::Output {
        Self {
            transport: self.transport & rhs.transport,
            payload: self.payload & rhs.payload,
        }
    }
}

/// A parsed (Transport) Feedback packet as specified in RFC 4585.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TransportFeedback<'a> {
    data: &'a [u8],
}

impl<'a> RtcpPacket for TransportFeedback<'a> {
    const MIN_PACKET_LEN: usize = 12;
    const PACKET_TYPE: u8 = 205;
}

impl<'a> RtcpPacketParser<'a> for TransportFeedback<'a> {
    fn parse(data: &'a [u8]) -> Result<Self, RtcpParseError> {
        parser::check_packet::<Self>(data)?;
        Ok(Self { data })
    }

    #[inline(always)]
    fn header_data(&self) -> [u8; 4] {
        self.data[..4].try_into().unwrap()
    }
}

impl<'a> TransportFeedback<'a> {
    /// Constructs a [`TransportFeedbackBuilder`] which refers to the provided [`FciBuilder`].
    ///
    /// Use [`TransportFeedback::builder_owned`] to return the [`TransportFeedbackBuilder`]
    /// from a function.
    pub fn builder(fci: &'a dyn FciBuilder<'a>) -> TransportFeedbackBuilder<'a> {
        TransportFeedbackBuilder {
            padding: 0,
            sender_ssrc: 0,
            media_ssrc: 0,
            fci: FciBuilderWrapper::Borrowed(fci),
        }
    }

    /// Constructs a [`TransportFeedbackBuilder`] which owns the provided [`FciBuilder`].
    ///
    /// This allows returning it from a function.
    ///
    /// **Warning:** this causes the [`FciBuilder`] to be heap-allocated.
    /// Use [`TransportFeedback::builder`] when possible.
    pub fn builder_owned(
        fci: impl FciBuilder<'static> + 'static,
    ) -> TransportFeedbackBuilder<'static> {
        TransportFeedbackBuilder {
            padding: 0,
            sender_ssrc: 0,
            media_ssrc: 0,
            fci: FciBuilderWrapper::Owned(Box::new(fci)),
        }
    }

    /// The (optional) padding used by this [`TransportFeedback`] packet
    pub fn padding(&self) -> Option<u8> {
        parser::parse_padding(self.data)
    }

    /// The SSRC of the sender sending this feedback
    pub fn sender_ssrc(&self) -> u32 {
        parser::parse_ssrc(self.data)
    }

    /// The SSRC of the media this packet refers to.  May be unset (0) in some feedback types.
    pub fn media_ssrc(&self) -> u32 {
        parser::parse_ssrc(&self.data[4..])
    }

    /// Parse the Feedback Control Information into a concrete type.
    ///
    /// Will fail if:
    /// * The FCI does not support transport feedback,
    /// * the feedback type does not match the FCI
    /// * The FCI implementation fails to parse the contained data
    pub fn parse_fci<F: FciParser<'a>>(&self) -> Result<F, RtcpParseError> {
        if F::PACKET_TYPE & FciFeedbackPacketType::TRANSPORT == FciFeedbackPacketType::NONE {
            return Err(RtcpParseError::WrongImplementation);
        }
        if parser::parse_count(self.data) != F::FCI_FORMAT {
            return Err(RtcpParseError::WrongImplementation);
        }
        F::parse(&self.data[12..])
    }
}

/// TransportFeedback packet builder
#[derive(Debug)]
#[must_use = "The builder must be built to be used"]
pub struct TransportFeedbackBuilder<'a> {
    padding: u8,
    sender_ssrc: u32,
    media_ssrc: u32,
    fci: FciBuilderWrapper<'a>,
}

impl<'a> TransportFeedbackBuilder<'a> {
    /// Set the SSRC this feedback packet is being sent from
    pub fn sender_ssrc(mut self, sender_ssrc: u32) -> Self {
        self.sender_ssrc = sender_ssrc;
        self
    }

    /// Set the SSRC this feedback packet is being directed towards.  May be 0 if the specific
    /// feedback type allows.
    pub fn media_ssrc(mut self, media_ssrc: u32) -> Self {
        self.media_ssrc = media_ssrc;
        self
    }

    /// Sets the number of padding bytes to use for this TransportFeedback packet.
    pub fn padding(mut self, padding: u8) -> Self {
        self.padding = padding;
        self
    }
}

#[inline]
fn fb_write_into<T: RtcpPacket>(
    feedback_type: FciFeedbackPacketType,
    buf: &mut [u8],
    sender_ssrc: u32,
    media_ssrc: u32,
    fci: &dyn FciBuilder,
    padding: u8,
) -> usize {
    if feedback_type & fci.supports_feedback_type() == FciFeedbackPacketType::NONE {
        return 0;
    }

    let fmt = fci.format();
    assert!(fmt <= 0x1f);
    let mut idx = writer::write_header_unchecked::<T>(padding, fmt, buf);

    let mut end = idx;
    end += 4;
    buf[idx..end].copy_from_slice(&sender_ssrc.to_be_bytes());
    idx = end;
    end += 4;
    buf[idx..end].copy_from_slice(&media_ssrc.to_be_bytes());
    idx = end;

    end += fci.write_into_unchecked(&mut buf[idx..]);

    end += writer::write_padding_unchecked(padding, &mut buf[idx..]);

    end
}

impl<'a> RtcpPacketWriter for TransportFeedbackBuilder<'a> {
    /// Calculates the size required to write this TransportFeedback packet.
    ///
    /// Returns an error if:
    ///
    /// * The FCI data is too large
    /// * The FCI fails to calculate a valid size
    fn calculate_size(&self) -> Result<usize, RtcpWriteError> {
        writer::check_padding(self.padding)?;

        if self.fci.supports_feedback_type() & FciFeedbackPacketType::TRANSPORT
            == FciFeedbackPacketType::NONE
        {
            return Err(RtcpWriteError::FciWrongFeedbackPacketType);
        }
        let fci_len = self.fci.calculate_size()?;

        Ok(TransportFeedback::MIN_PACKET_LEN + pad_to_4bytes(fci_len))
    }

    /// Write this TransportFeedback packet data into `buf` without any validity checks.
    ///
    /// Returns the number of bytes written.
    ///
    /// # Panic
    ///
    /// Panics if the buf is not large enough.
    #[inline]
    fn write_into_unchecked(&self, buf: &mut [u8]) -> usize {
        fb_write_into::<TransportFeedback>(
            FciFeedbackPacketType::TRANSPORT,
            buf,
            self.sender_ssrc,
            self.media_ssrc,
            self.fci.as_ref(),
            self.padding,
        )
    }

    fn get_padding(&self) -> Option<u8> {
        if self.padding == 0 {
            return None;
        }

        Some(self.padding)
    }
}

/// A parsed (Transport) Feedback packet as specified in RFC 4585.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PayloadFeedback<'a> {
    data: &'a [u8],
}

impl<'a> RtcpPacket for PayloadFeedback<'a> {
    const MIN_PACKET_LEN: usize = 12;
    const PACKET_TYPE: u8 = 206;
}

impl<'a> RtcpPacketParser<'a> for PayloadFeedback<'a> {
    fn parse(data: &'a [u8]) -> Result<Self, RtcpParseError> {
        parser::check_packet::<Self>(data)?;
        Ok(Self { data })
    }

    #[inline(always)]
    fn header_data(&self) -> [u8; 4] {
        self.data[..4].try_into().unwrap()
    }
}

impl<'a> PayloadFeedback<'a> {
    /// Constructs a [`PayloadFeedbackBuilder`] which refers to the provided [`FciBuilder`].
    ///
    /// Use [`PayloadFeedback::builder_owned`] to return the [`PayloadFeedbackBuilder`] from a function.
    pub fn builder(fci: &'a dyn FciBuilder<'a>) -> PayloadFeedbackBuilder<'a> {
        PayloadFeedbackBuilder {
            padding: 0,
            sender_ssrc: 0,
            media_ssrc: 0,
            fci: FciBuilderWrapper::Borrowed(fci),
        }
    }

    /// Constructs a [`PayloadFeedbackBuilder`] which owns the provided [`FciBuilder`].
    ///
    /// This allows returning it from a function.
    ///
    /// **Warning:** this causes the [`FciBuilder`] to be heap-allocated.
    /// Use [`PayloadFeedback::builder`] when possible.
    pub fn builder_owned(
        fci: impl FciBuilder<'static> + 'static,
    ) -> PayloadFeedbackBuilder<'static> {
        PayloadFeedbackBuilder {
            padding: 0,
            sender_ssrc: 0,
            media_ssrc: 0,
            fci: FciBuilderWrapper::Owned(Box::new(fci)),
        }
    }

    /// The (optional) padding used by this [`PayloadFeedback`] packet
    pub fn padding(&self) -> Option<u8> {
        parser::parse_padding(self.data)
    }

    /// The SSRC of the sender sending this feedback
    pub fn sender_ssrc(&self) -> u32 {
        parser::parse_ssrc(self.data)
    }

    /// The SSRC of the media this packet refers to.  May be unset (0) in some feedback types.
    pub fn media_ssrc(&self) -> u32 {
        parser::parse_ssrc(&self.data[4..])
    }

    /// Parse the Feedback Control Information into a concrete type.
    ///
    /// Will fail if:
    /// * The FCI does not support payload feedback,
    /// * the feedback type does not match the FCI
    /// * The FCI implementation fails to parse the contained data
    pub fn parse_fci<F: FciParser<'a>>(&self) -> Result<F, RtcpParseError> {
        if F::PACKET_TYPE & FciFeedbackPacketType::PAYLOAD == FciFeedbackPacketType::NONE {
            return Err(RtcpParseError::WrongImplementation);
        }
        if parser::parse_count(self.data) != F::FCI_FORMAT {
            return Err(RtcpParseError::WrongImplementation);
        }
        F::parse(&self.data[12..])
    }
}

/// TransportFeedback packet builder
#[derive(Debug)]
#[must_use = "The builder must be built to be used"]
pub struct PayloadFeedbackBuilder<'a> {
    padding: u8,
    sender_ssrc: u32,
    media_ssrc: u32,
    fci: FciBuilderWrapper<'a>,
}

impl<'a> PayloadFeedbackBuilder<'a> {
    /// Set the SSRC this feedback packet is being sent from
    pub fn sender_ssrc(mut self, sender_ssrc: u32) -> Self {
        self.sender_ssrc = sender_ssrc;
        self
    }

    /// Set the SSRC this feedback packet is being directed towards.  May be 0 if the specific
    /// feedback type allows.
    pub fn media_ssrc(mut self, media_ssrc: u32) -> Self {
        self.media_ssrc = media_ssrc;
        self
    }

    /// Sets the number of padding bytes to use for this TransportFeedback packet.
    pub fn padding(mut self, padding: u8) -> Self {
        self.padding = padding;
        self
    }
}

impl<'a> RtcpPacketWriter for PayloadFeedbackBuilder<'a> {
    /// Calculates the size required to write this PayloadFeedback packet.
    ///
    /// Returns an error if:
    ///
    /// * The FCI data is too large
    /// * The FCI fails to calculate a valid size
    fn calculate_size(&self) -> Result<usize, RtcpWriteError> {
        writer::check_padding(self.padding)?;

        if self.fci.supports_feedback_type() & FciFeedbackPacketType::PAYLOAD
            == FciFeedbackPacketType::NONE
        {
            return Err(RtcpWriteError::FciWrongFeedbackPacketType);
        }
        let fci_len = self.fci.calculate_size()?;

        Ok(PayloadFeedback::MIN_PACKET_LEN + pad_to_4bytes(fci_len))
    }

    /// Write this TransportFeedback packet data into `buf` without any validity checks.
    ///
    /// Returns the number of bytes written.
    ///
    /// # Panic
    ///
    /// Panics if the buf is not large enough.
    #[inline]
    fn write_into_unchecked(&self, buf: &mut [u8]) -> usize {
        fb_write_into::<PayloadFeedback>(
            FciFeedbackPacketType::PAYLOAD,
            buf,
            self.sender_ssrc,
            self.media_ssrc,
            self.fci.as_ref(),
            self.padding,
        )
    }

    fn get_padding(&self) -> Option<u8> {
        if self.padding == 0 {
            return None;
        }

        Some(self.padding)
    }
}

/// Trait for parsing FCI data in [`TransportFeedback`] or [`PayloadFeedback`] packets
pub trait FciParser<'a>: Sized {
    const PACKET_TYPE: FciFeedbackPacketType;
    const FCI_FORMAT: u8;

    /// Parse the provided FCI data
    fn parse(data: &'a [u8]) -> Result<Self, RtcpParseError>;
}

/// Stack or heap allocated [`FciBuilder`] wrapper.
///
/// This wrapper allows borrowing or owning an [`FciBuilder`] without
/// propagating the concrete type of the [`FciBuilder`] to types such as
/// [`PayloadFeedbackBuilder`] or [`TransportFeedback`]. This is needed for
/// these types to be included in collections such as [`crate::CompoundBuilder`].
///
/// `Cow` from `std` would not be suitable here because it would require
/// declaring the `B` type parameter as an implementer of `ToOwned`,
/// which is not object-safe.
#[derive(Debug)]
enum FciBuilderWrapper<'a> {
    Borrowed(&'a dyn FciBuilder<'a>),
    // Note: using `'a` and not `'static` here to help with the implementations
    // of `deref()` and `as_ref()`. This enum is private and the `Owned` variant
    // can only be constructed from `PayloadFeedbackBuilder::builder_owned` &
    // `TransportFeedback::builder_owned` which constrain the `FciBuilder` to be `'static`.
    Owned(Box<dyn FciBuilder<'a>>),
}

impl<'a, T: FciBuilder<'a>> From<&'a T> for FciBuilderWrapper<'a> {
    fn from(value: &'a T) -> Self {
        FciBuilderWrapper::Borrowed(value)
    }
}

impl<'a> std::convert::AsRef<dyn FciBuilder<'a> + 'a> for FciBuilderWrapper<'a> {
    fn as_ref(&self) -> &(dyn FciBuilder<'a> + 'a) {
        match self {
            FciBuilderWrapper::Borrowed(this) => *this,
            FciBuilderWrapper::Owned(this) => this.borrow(),
        }
    }
}

impl<'a> std::ops::Deref for FciBuilderWrapper<'a> {
    type Target = dyn FciBuilder<'a> + 'a;

    fn deref(&self) -> &(dyn FciBuilder<'a> + 'a) {
        match self {
            FciBuilderWrapper::Borrowed(this) => *this,
            FciBuilderWrapper::Owned(this) => this.borrow(),
        }
    }
}

/// Trait for writing a particular FCI implementation with a [`TransportFeedbackBuilder`] or
/// [`PayloadFeedbackBuilder`].
pub trait FciBuilder<'a>: RtcpPacketWriter {
    /// The format field value to place in the RTCP header
    fn format(&self) -> u8;
    /// The type of feedback packet this FCI data supports being placed in
    fn supports_feedback_type(&self) -> FciFeedbackPacketType;
}