Skip to main content

rtci_sdp/attribute/
source.rs

1//! `a=ssrc` and `a=ssrc-group` (RFC 5576).
2
3use std::fmt;
4
5use shared::error::Result;
6
7use super::{Fmtp, Msid, TypedAttribute};
8use crate::grammar::{self, syntax};
9
10/// `ssrc-id`: "0 .. 2**32 - 1", written without leading zeroes.
11fn ssrc_id(what: &str, value: &str) -> Result<u32> {
12    grammar::digits_no_leading_zero(what, value)
13}
14
15/// `a=ssrc:<ssrc-id> <attribute>[:<value>]` (RFC 5576 section 4.1): one source attribute of
16/// one synchronization source.
17///
18/// A source with several attributes has several lines. The source attributes RFC 5576
19/// defines are `cname` (section 6.1), `previous-ssrc` (section 6.2) and `fmtp`
20/// (section 6.3); WebRTC endpoints also write `msid` (draft-ietf-mmusic-msid, before
21/// RFC 8830 moved it to the media level) and the unregistered `mslabel` and `label`. Any
22/// other attribute name is kept: [`Ssrc::attribute`] and [`Ssrc::value`] always hold what
23/// the line said.
24#[derive(Debug, Clone, PartialEq, Eq)]
25pub struct Ssrc {
26    /// The synchronization source.
27    pub id: u32,
28    /// The source attribute's name, a token.
29    pub attribute: String,
30    /// The source attribute's value: what follows the name's colon.
31    pub value: Option<String>,
32}
33
34impl Ssrc {
35    /// The value of this line's source attribute when it is `name`.
36    fn value_if(&self, name: &str) -> Option<&str> {
37        if self.attribute == name {
38            self.value.as_deref()
39        } else {
40            None
41        }
42    }
43
44    /// `cname:<cname>` (RFC 5576 section 6.1): the source's RTCP canonical name.
45    pub fn cname(&self) -> Option<&str> {
46        self.value_if("cname")
47    }
48
49    /// `previous-ssrc:<ssrc-id> *(SP <ssrc-id>)` (RFC 5576 section 6.2): the SSRCs this
50    /// source used before. `None` when this line is another attribute.
51    pub fn previous_ssrcs(&self) -> Option<Result<Vec<u32>>> {
52        let value = self.value_if("previous-ssrc")?;
53        Some(grammar::fields("previous-ssrc", value).and_then(|ids| {
54            ids.into_iter()
55                .map(|id| ssrc_id("previous-ssrc", id))
56                .collect()
57        }))
58    }
59
60    /// `fmtp:<format> <format specific parameters>` (RFC 5576 section 6.3): format
61    /// parameters that apply to this source only.
62    pub fn fmtp(&self) -> Option<Result<Fmtp>> {
63        self.value_if("fmtp").map(Fmtp::parse)
64    }
65
66    /// `msid:<id> [<appdata>]`: the MediaStream and track of this source, as endpoints
67    /// wrote it before RFC 8830.
68    pub fn msid(&self) -> Option<Result<Msid>> {
69        self.value_if("msid").map(Msid::parse)
70    }
71}
72
73impl TypedAttribute for Ssrc {
74    const NAME: &'static str = "ssrc";
75
76    fn parse(value: &str) -> Result<Self> {
77        let Some((id, attribute)) = value.split_once(' ') else {
78            return Err(syntax("a=ssrc", value));
79        };
80        let id = ssrc_id("a=ssrc", id)?;
81        let (name, attribute_value) = match attribute.split_once(':') {
82            Some((name, v)) => (name, Some(v)),
83            None => (attribute, None),
84        };
85        if !grammar::is_token(name) || !attribute_value.is_none_or(grammar::is_byte_string) {
86            return Err(syntax("a=ssrc", value));
87        }
88        let parsed = Ssrc {
89            id,
90            attribute: name.to_owned(),
91            value: attribute_value.map(str::to_owned),
92        };
93        // The attributes whose grammar is known are checked here, so that a parsed `Ssrc`
94        // has none that is malformed.
95        match name {
96            "cname" if parsed.value.is_none() => return Err(syntax("a=ssrc cname", value)),
97            "previous-ssrc" => {
98                parsed
99                    .previous_ssrcs()
100                    .ok_or_else(|| syntax("a=ssrc previous-ssrc", value))??;
101            }
102            "fmtp" => {
103                parsed
104                    .fmtp()
105                    .ok_or_else(|| syntax("a=ssrc fmtp", value))??;
106            }
107            "msid" => {
108                parsed
109                    .msid()
110                    .ok_or_else(|| syntax("a=ssrc msid", value))??;
111            }
112            _ => {}
113        }
114        Ok(parsed)
115    }
116}
117
118impl fmt::Display for Ssrc {
119    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
120        write!(f, "{} {}", self.id, self.attribute)?;
121        if let Some(value) = &self.value {
122            write!(f, ":{value}")?;
123        }
124        Ok(())
125    }
126}
127
128/// `a=ssrc-group:<semantics> *(SP <ssrc-id>)` (RFC 5576 section 4.2).
129///
130/// The semantics is a token: `FID` (flow identification: a stream and its retransmission,
131/// RFC 4588), `FEC` (RFC 5576), `FEC-FR` (RFC 5956), `DUP` (RFC 7104), `SIM` (the
132/// pre-standard simulcast grouping some endpoints write) or any other.
133#[derive(Debug, Clone, PartialEq, Eq)]
134pub struct SsrcGroup {
135    /// The semantics token, as written.
136    pub semantics: String,
137    /// The grouped sources, in order: the order carries meaning (in `FID`, the first is the
138    /// media stream).
139    pub ssrcs: Vec<u32>,
140}
141
142impl TypedAttribute for SsrcGroup {
143    const NAME: &'static str = "ssrc-group";
144
145    fn parse(value: &str) -> Result<Self> {
146        let mut fields = grammar::fields("a=ssrc-group", value)?.into_iter();
147        let semantics = fields.next().unwrap_or_default();
148        if !grammar::is_token(semantics) {
149            return Err(syntax("a=ssrc-group", value));
150        }
151        Ok(SsrcGroup {
152            semantics: semantics.to_owned(),
153            ssrcs: fields
154                .map(|id| ssrc_id("a=ssrc-group", id))
155                .collect::<Result<_>>()?,
156        })
157    }
158}
159
160impl fmt::Display for SsrcGroup {
161    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
162        f.write_str(&self.semantics)?;
163        for ssrc in &self.ssrcs {
164            write!(f, " {ssrc}")?;
165        }
166        Ok(())
167    }
168}