Skip to main content

rtci_rtcp/source_description/
mod.rs

1#[cfg(test)]
2mod source_description_items_test;
3#[cfg(test)]
4mod source_description_test;
5
6use crate::{header::*, packet::*, util::*};
7use shared::{
8    error::{Error, Result},
9    marshal::{Marshal, MarshalSize, Unmarshal},
10};
11
12use bytes::{Buf, BufMut, Bytes};
13use std::any::Any;
14use std::fmt;
15
16const SDES_SOURCE_LEN: usize = 4;
17const SDES_TYPE_LEN: usize = 1;
18const SDES_TYPE_OFFSET: usize = 0;
19const SDES_OCTET_COUNT_LEN: usize = 1;
20const SDES_OCTET_COUNT_OFFSET: usize = 1;
21const SDES_MAX_OCTET_COUNT: usize = (1 << 8) - 1;
22const SDES_TEXT_OFFSET: usize = 2;
23
24/// SDESType is the item type used in the RTCP SDES control packet.
25/// RTP SDES item types registered with IANA. See: <https://www.iana.org/assignments/rtp-parameters/rtp-parameters.xhtml#rtp-parameters-5>
26///
27/// The enum converts to and from the type octet with `u8::from` / `SdesType::from`. The
28/// registry grows, so an item of a type that is not named here is kept as
29/// [`SdesType::Other`]: a receiver skips such an item by its length (RFC 3550 §6.5).
30#[derive(Default, Debug, Copy, Clone, PartialEq, Eq)]
31#[non_exhaustive]
32pub enum SdesType {
33    #[default]
34    /// End of the SDES item list ([RFC 3550] §6.5).
35    SdesEnd, // 0, end of SDES list                RFC 3550, 6.5
36    /// CNAME: the canonical end-point identifier, which ties an SSRC to a participant.
37    ///
38    /// The one item WebRTC always sends — it is how a receiver associates streams that belong
39    /// together.
40    SdesCname, // 1, canonical name                  RFC 3550, 6.5.1
41    /// NAME: the participant's display name.
42    SdesName, // 2, user name                       RFC 3550, 6.5.2
43    /// EMAIL: the participant's email address.
44    SdesEmail, // 3, user's electronic mail address  RFC 3550, 6.5.3
45    /// PHONE: the participant's phone number.
46    SdesPhone, // 4, user's phone number             RFC 3550, 6.5.4
47    /// LOC: the participant's geographic location.
48    SdesLocation, // 5, geographic user location        RFC 3550, 6.5.5
49    /// TOOL: the name and version of the sending application.
50    SdesTool, // 6, name of application or tool     RFC 3550, 6.5.6
51    /// NOTE: a transient note about the source, such as "on hold".
52    SdesNote, // 7, notice about the source         RFC 3550, 6.5.7
53    /// PRIV: a private extension: a prefix that names it, and a value
54    /// ([`SourceDescriptionItem::private`]).
55    SdesPrivate, // 8, private extensions              RFC 3550, 6.5.8
56    /// RtpStreamId: the RID of the source stream ([RFC 8852] §3.1), ASCII, not null terminated.
57    ///
58    /// [RFC 8852]: https://datatracker.ietf.org/doc/html/rfc8852
59    SdesRtpStreamId, // 12, RFC 8852, 3.1
60    /// RepairedRtpStreamId: on a redundancy stream, the RID of the source stream it repairs
61    /// ([RFC 8852] §3.2).
62    ///
63    /// [RFC 8852]: https://datatracker.ietf.org/doc/html/rfc8852
64    SdesRepairedRtpStreamId, // 13, RFC 8852, 3.2
65    /// MID: the media identification that ties the source to an SDP media section
66    /// ([RFC 8843] §15.1, carried as [RFC 7941] describes).
67    ///
68    /// [RFC 8843]: https://datatracker.ietf.org/doc/html/rfc8843
69    /// [RFC 7941]: https://datatracker.ietf.org/doc/html/rfc7941
70    SdesMid, // 15, RFC 8843, 15.1
71    /// An item type that is not named above, with its type octet.
72    Other(u8),
73}
74
75impl fmt::Display for SdesType {
76    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77        let s = match self {
78            SdesType::SdesEnd => "END",
79            SdesType::SdesCname => "CNAME",
80            SdesType::SdesName => "NAME",
81            SdesType::SdesEmail => "EMAIL",
82            SdesType::SdesPhone => "PHONE",
83            SdesType::SdesLocation => "LOC",
84            SdesType::SdesTool => "TOOL",
85            SdesType::SdesNote => "NOTE",
86            SdesType::SdesPrivate => "PRIV",
87            SdesType::SdesRtpStreamId => "RtpStreamId",
88            SdesType::SdesRepairedRtpStreamId => "RepairedRtpStreamId",
89            SdesType::SdesMid => "MID",
90            SdesType::Other(t) => return write!(f, "SDES{t}"),
91        };
92        write!(f, "{s}")
93    }
94}
95
96impl From<u8> for SdesType {
97    fn from(b: u8) -> Self {
98        match b {
99            0 => SdesType::SdesEnd,
100            1 => SdesType::SdesCname,
101            2 => SdesType::SdesName,
102            3 => SdesType::SdesEmail,
103            4 => SdesType::SdesPhone,
104            5 => SdesType::SdesLocation,
105            6 => SdesType::SdesTool,
106            7 => SdesType::SdesNote,
107            8 => SdesType::SdesPrivate,
108            12 => SdesType::SdesRtpStreamId,
109            13 => SdesType::SdesRepairedRtpStreamId,
110            15 => SdesType::SdesMid,
111            other => SdesType::Other(other),
112        }
113    }
114}
115
116impl From<SdesType> for u8 {
117    fn from(t: SdesType) -> Self {
118        match t {
119            SdesType::SdesEnd => 0,
120            SdesType::SdesCname => 1,
121            SdesType::SdesName => 2,
122            SdesType::SdesEmail => 3,
123            SdesType::SdesPhone => 4,
124            SdesType::SdesLocation => 5,
125            SdesType::SdesTool => 6,
126            SdesType::SdesNote => 7,
127            SdesType::SdesPrivate => 8,
128            SdesType::SdesRtpStreamId => 12,
129            SdesType::SdesRepairedRtpStreamId => 13,
130            SdesType::SdesMid => 15,
131            SdesType::Other(other) => other,
132        }
133    }
134}
135
136/// A SourceDescriptionChunk contains items describing a single RTP source
137#[derive(Debug, PartialEq, Eq, Default, Clone)]
138pub struct SourceDescriptionChunk {
139    /// The source (ssrc) or contributing source (csrc) identifier this packet describes
140    pub source: u32,
141    /// The items describing this source.
142    pub items: Vec<SourceDescriptionItem>,
143}
144
145impl SourceDescriptionChunk {
146    fn raw_size(&self) -> usize {
147        let mut len = SDES_SOURCE_LEN;
148        for it in &self.items {
149            len += it.marshal_size();
150        }
151        len += SDES_TYPE_LEN; // for terminating null octet
152        len
153    }
154}
155
156impl MarshalSize for SourceDescriptionChunk {
157    fn marshal_size(&self) -> usize {
158        let l = self.raw_size();
159        // align to 32-bit boundary
160        l + get_padding_size(l)
161    }
162}
163
164impl Marshal for SourceDescriptionChunk {
165    /// Marshal encodes the SourceDescriptionChunk in binary
166    fn marshal_to(&self, mut buf: &mut [u8]) -> Result<usize> {
167        if buf.remaining_mut() < self.marshal_size() {
168            return Err(Error::BufferTooShort);
169        }
170        /*
171         *  +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
172         *  |                          SSRC/CSRC_1                          |
173         *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
174         *  |                           SDES items                          |
175         *  |                              ...                              |
176         *  +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
177         */
178
179        buf.put_u32(self.source);
180
181        for it in &self.items {
182            let n = it.marshal_to(buf)?;
183            buf = &mut buf[n..];
184        }
185
186        // The list of items in each chunk MUST be terminated by one or more null octets
187        buf.put_u8(SdesType::SdesEnd.into());
188
189        // additional null octets MUST be included if needed to pad until the next 32-bit boundary
190        // (null octets: this is not the padding of the P bit, whose last octet is a count)
191        buf.put_bytes(0, get_padding_size(self.raw_size()));
192        Ok(self.marshal_size())
193    }
194}
195
196impl Unmarshal for SourceDescriptionChunk {
197    /// Unmarshal decodes the SourceDescriptionChunk from binary
198    fn unmarshal<B>(raw_packet: &mut B) -> Result<Self>
199    where
200        Self: Sized,
201        B: Buf,
202    {
203        /*
204         *  +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
205         *  |                          SSRC/CSRC_1                          |
206         *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
207         *  |                           SDES items                          |
208         *  |                              ...                              |
209         *  +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
210         */
211        if raw_packet.remaining() < (SDES_SOURCE_LEN + SDES_TYPE_LEN) {
212            return Err(Error::PacketTooShort);
213        }
214
215        let source = raw_packet.get_u32();
216
217        // Octets of this chunk read so far. A chunk starts on a 32-bit boundary, so this also
218        // says how far the next boundary is.
219        let mut offset = SDES_SOURCE_LEN;
220        let mut items = vec![];
221        loop {
222            // "The list of items in each chunk MUST be terminated by one or more null octets":
223            // a chunk that runs out without one is cut short.
224            let item = SourceDescriptionItem::unmarshal(raw_packet)?;
225            if item.sdes_type == SdesType::SdesEnd {
226                // offset + 1 (one byte for SdesEnd), then null octets up to the boundary.
227                let padding_len = get_padding_size(offset + 1);
228                if raw_packet.remaining() < padding_len {
229                    return Err(Error::PacketTooShort);
230                }
231                raw_packet.advance(padding_len);
232                return Ok(SourceDescriptionChunk { source, items });
233            }
234            // Every item is kept, of a known type or not: an unknown one is skipped by its
235            // length here, and it is the reader of `items` that passes over it.
236            offset += item.marshal_size();
237            items.push(item);
238        }
239    }
240}
241
242/// A SourceDescriptionItem is a part of a SourceDescription that describes a stream.
243#[derive(Debug, PartialEq, Eq, Default, Clone)]
244pub struct SourceDescriptionItem {
245    /// The type identifier for this item. eg, SDESCNAME for canonical name description.
246    ///
247    /// Type zero or SDESEnd is interpreted as the end of an item list and cannot be used.
248    pub sdes_type: SdesType,
249    /// Text is a unicode text blob associated with the item. Its meaning varies based on the item's Type.
250    pub text: Bytes,
251}
252
253impl SourceDescriptionItem {
254    /// A PRIV item (RFC 3550 §6.5.8): `prefix` names the extension, `value` is its content.
255    ///
256    /// The two share the item's 255 octets with the prefix length octet, so together they are
257    /// at most 254 octets long.
258    pub fn private(prefix: &[u8], value: &[u8]) -> Result<Self> {
259        if 1 + prefix.len() + value.len() > SDES_MAX_OCTET_COUNT {
260            return Err(Error::SdesTextTooLong);
261        }
262        let mut text = Vec::with_capacity(1 + prefix.len() + value.len());
263        text.push(prefix.len() as u8);
264        text.extend_from_slice(prefix);
265        text.extend_from_slice(value);
266        Ok(SourceDescriptionItem {
267            sdes_type: SdesType::SdesPrivate,
268            text: Bytes::from(text),
269        })
270    }
271
272    /// The prefix and the value of a PRIV item, or `None` when this is not one or its prefix
273    /// length runs past the item.
274    pub fn as_private(&self) -> Option<(Bytes, Bytes)> {
275        if self.sdes_type != SdesType::SdesPrivate {
276            return None;
277        }
278        let prefix_len = *self.text.first()? as usize;
279        if 1 + prefix_len > self.text.len() {
280            return None;
281        }
282        Some((
283            self.text.slice(1..1 + prefix_len),
284            self.text.slice(1 + prefix_len..),
285        ))
286    }
287}
288
289impl MarshalSize for SourceDescriptionItem {
290    fn marshal_size(&self) -> usize {
291        /*
292         *   0                   1                   2                   3
293         *   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
294         *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
295         *  |    CNAME=1    |     length    | user and domain name        ...
296         *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
297         */
298        SDES_TYPE_LEN + SDES_OCTET_COUNT_LEN + self.text.len()
299    }
300}
301
302impl Marshal for SourceDescriptionItem {
303    /// Marshal encodes the SourceDescriptionItem in binary
304    fn marshal_to(&self, mut buf: &mut [u8]) -> Result<usize> {
305        /*
306         *   0                   1                   2                   3
307         *   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
308         *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
309         *  |    CNAME=1    |     length    | user and domain name        ...
310         *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
311         */
312
313        // Type zero ends the list and cannot be an item, whichever way it is spelled.
314        let sdes_type = u8::from(self.sdes_type);
315        if sdes_type == 0 {
316            return Err(Error::SdesMissingType);
317        }
318
319        if buf.remaining_mut() < self.marshal_size() {
320            return Err(Error::BufferTooShort);
321        }
322
323        buf.put_u8(sdes_type);
324
325        if self.text.len() > SDES_MAX_OCTET_COUNT {
326            return Err(Error::SdesTextTooLong);
327        }
328        buf.put_u8(self.text.len() as u8);
329        buf.put(self.text.clone());
330
331        //no padding for each SourceDescriptionItem
332        Ok(self.marshal_size())
333    }
334}
335
336impl Unmarshal for SourceDescriptionItem {
337    /// Unmarshal decodes the SourceDescriptionItem from binary
338    fn unmarshal<B>(raw_packet: &mut B) -> Result<Self>
339    where
340        Self: Sized,
341        B: Buf,
342    {
343        /*
344         *   0                   1                   2                   3
345         *   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
346         *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
347         *  |    CNAME=1    |     length    | user and domain name        ...
348         *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
349         */
350        let raw_packet_len = raw_packet.remaining();
351        if raw_packet_len < SDES_TYPE_LEN {
352            return Err(Error::PacketTooShort);
353        }
354
355        let sdes_type = SdesType::from(raw_packet.get_u8());
356        if sdes_type == SdesType::SdesEnd {
357            return Ok(SourceDescriptionItem {
358                sdes_type,
359                text: Bytes::new(),
360            });
361        }
362
363        if raw_packet_len < (SDES_TYPE_LEN + SDES_OCTET_COUNT_LEN) {
364            return Err(Error::PacketTooShort);
365        }
366
367        let octet_count = raw_packet.get_u8() as usize;
368        if SDES_TEXT_OFFSET + octet_count > raw_packet_len {
369            return Err(Error::PacketTooShort);
370        }
371
372        let text = raw_packet.copy_to_bytes(octet_count);
373
374        Ok(SourceDescriptionItem { sdes_type, text })
375    }
376}
377
378/// A SourceDescription (SDES) packet describes the sources in an RTP stream.
379#[derive(Debug, Default, PartialEq, Eq, Clone)]
380pub struct SourceDescription {
381    /// One chunk per source described by this packet.
382    pub chunks: Vec<SourceDescriptionChunk>,
383}
384
385impl fmt::Display for SourceDescription {
386    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
387        let mut out = "Source Description:\n".to_string();
388        for c in &self.chunks {
389            out += format!("\t{:x}\n", c.source).as_str();
390            for it in &c.items {
391                out += format!("\t\t{it:?}\n").as_str();
392            }
393        }
394        write!(f, "{out}")
395    }
396}
397
398impl Packet for SourceDescription {
399    /// Header returns the Header associated with this packet.
400    fn header(&self) -> Header {
401        Header {
402            // Every chunk ends on a 32-bit boundary, so the packet does too.
403            padding: false,
404            count: self.chunks.len() as u8,
405            packet_type: PacketType::SourceDescription,
406            length: ((self.marshal_size() / 4) - 1) as u16,
407        }
408    }
409
410    /// destination_ssrc returns an array of SSRC values that this packet refers to.
411    fn destination_ssrc(&self) -> Vec<u32> {
412        self.chunks.iter().map(|x| x.source).collect()
413    }
414
415    fn raw_size(&self) -> usize {
416        let mut chunks_length = 0;
417        for c in &self.chunks {
418            chunks_length += c.marshal_size();
419        }
420
421        HEADER_LENGTH + chunks_length
422    }
423
424    fn as_any(&self) -> &dyn Any {
425        self
426    }
427
428    fn equal(&self, other: &dyn Packet) -> bool {
429        other.as_any().downcast_ref::<SourceDescription>() == Some(self)
430    }
431
432    fn cloned(&self) -> Box<dyn Packet> {
433        Box::new(self.clone())
434    }
435}
436
437impl MarshalSize for SourceDescription {
438    fn marshal_size(&self) -> usize {
439        let l = self.raw_size();
440        // align to 32-bit boundary
441        l + get_padding_size(l)
442    }
443}
444
445impl Marshal for SourceDescription {
446    /// Marshal encodes the SourceDescription in binary
447    fn marshal_to(&self, mut buf: &mut [u8]) -> Result<usize> {
448        if self.chunks.len() > COUNT_MAX {
449            return Err(Error::TooManyChunks);
450        }
451
452        if buf.remaining_mut() < self.marshal_size() {
453            return Err(Error::BufferTooShort);
454        }
455
456        /*
457         *         0                   1                   2                   3
458         *         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
459         *        +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
460         * header |V=2|P|    SC   |  PT=SDES=202  |             length            |
461         *        +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
462         * chunk  |                          SSRC/CSRC_1                          |
463         *   1    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
464         *        |                           SDES items                          |
465         *        |                              ...                              |
466         *        +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
467         * chunk  |                          SSRC/CSRC_2                          |
468         *   2    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
469         *        |                           SDES items                          |
470         *        |                              ...                              |
471         *        +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
472         */
473
474        let h = self.header();
475        let n = h.marshal_to(buf)?;
476        buf = &mut buf[n..];
477
478        for c in &self.chunks {
479            let n = c.marshal_to(buf)?;
480            buf = &mut buf[n..];
481        }
482
483        if h.padding {
484            put_padding(buf, self.raw_size());
485        }
486
487        Ok(self.marshal_size())
488    }
489}
490
491impl Unmarshal for SourceDescription {
492    /// Unmarshal decodes the SourceDescription from binary
493    fn unmarshal<B>(raw_packet: &mut B) -> Result<Self>
494    where
495        Self: Sized,
496        B: Buf,
497    {
498        /*
499         *         0                   1                   2                   3
500         *         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
501         *        +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
502         * header |V=2|P|    SC   |  PT=SDES=202  |             length            |
503         *        +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
504         * chunk  |                          SSRC/CSRC_1                          |
505         *   1    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
506         *        |                           SDES items                          |
507         *        |                              ...                              |
508         *        +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
509         * chunk  |                          SSRC/CSRC_2                          |
510         *   2    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
511         *        |                           SDES items                          |
512         *        |                              ...                              |
513         *        +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
514         */
515        let (h, mut body) = read_packet(raw_packet)?;
516        if h.packet_type != PacketType::SourceDescription {
517            return Err(Error::WrongType);
518        }
519
520        // SC chunks, each ending on a 32-bit boundary, and nothing after them.
521        let mut chunks = Vec::with_capacity(h.count as usize);
522        for _ in 0..h.count {
523            chunks.push(SourceDescriptionChunk::unmarshal(&mut body)?);
524        }
525        if body.has_remaining() {
526            return Err(Error::InvalidHeader);
527        }
528
529        Ok(SourceDescription { chunks })
530    }
531}