Skip to main content

rtci_sdp/attribute/
grouping.rs

1//! `a=group`, `a=mid` (RFC 5888, RFC 9143) and `a=msid`, `a=msid-semantic` (RFC 8830).
2
3use std::fmt;
4
5use shared::error::Result;
6
7use super::{TypedAttribute, string_attribute};
8use crate::description::session::SEMANTIC_TOKEN_BUNDLE;
9use crate::grammar::{self, syntax};
10
11/// `a=group:<semantics> *(SP <identification-tag>)` (RFC 5888 section 5).
12///
13/// The semantics is a token: `LS` and `FID` (RFC 5888), `BUNDLE` (RFC 9143), `SRF`
14/// (RFC 3524), `ANAT` (RFC 4091), `FEC` (RFC 4756), `FEC-FR` (RFC 5956), `CS` (RFC 5432),
15/// `DDP` (RFC 5583), `DUP` (RFC 7104), or any other registered one. A group may be empty:
16/// RFC 9143 section 7.3.1 has an answerer write `a=group:BUNDLE` with no tag.
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct Group {
19    /// The semantics token, as written (it is case-sensitive).
20    pub semantics: String,
21    /// The identification tags (the `a=mid` values) of the grouped m= sections, in order.
22    pub mids: Vec<String>,
23}
24
25impl Group {
26    /// Whether this is a `BUNDLE` group (RFC 9143).
27    pub fn is_bundle(&self) -> bool {
28        self.semantics == SEMANTIC_TOKEN_BUNDLE
29    }
30
31    /// Whether `mid` is in the group.
32    pub fn contains(&self, mid: &str) -> bool {
33        self.mids.iter().any(|m| m == mid)
34    }
35}
36
37impl TypedAttribute for Group {
38    const NAME: &'static str = "group";
39
40    fn parse(value: &str) -> Result<Self> {
41        let mut fields = grammar::fields("a=group", value)?.into_iter();
42        // `fields` never returns an empty list.
43        let semantics = fields.next().unwrap_or_default();
44        let mids: Vec<String> = fields.map(str::to_owned).collect();
45        if !grammar::is_token(semantics) || !mids.iter().all(|m| grammar::is_token(m)) {
46            return Err(syntax("a=group", value));
47        }
48        Ok(Group {
49            semantics: semantics.to_owned(),
50            mids,
51        })
52    }
53}
54
55impl fmt::Display for Group {
56    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
57        f.write_str(&self.semantics)?;
58        for mid in &self.mids {
59            write!(f, " {mid}")?;
60        }
61        Ok(())
62    }
63}
64
65string_attribute!(
66    /// `a=mid:<identification-tag>` (RFC 5888 section 4): a token.
67    Mid,
68    "mid",
69    "a=mid",
70    |v| grammar::is_token(v)
71);
72
73/// `1*64token-char`.
74fn is_msid_token(value: &str) -> bool {
75    value.len() <= 64 && grammar::is_token(value)
76}
77
78/// `a=msid:<msid-id> [SP <msid-appdata>]` (RFC 8830 section 2).
79///
80/// The id names a MediaStream, or is `-` for a track that is in none (RFC 9429 section
81/// 5.2.1); the application data, when present, is the track id. A media section has one
82/// line per MediaStream its track is in.
83#[derive(Debug, Clone, PartialEq, Eq, Hash)]
84pub struct Msid {
85    /// The MediaStream id: 1 to 64 token characters.
86    pub id: String,
87    /// The application data: 1 to 64 token characters.
88    pub appdata: Option<String>,
89}
90
91impl TypedAttribute for Msid {
92    const NAME: &'static str = "msid";
93
94    fn parse(value: &str) -> Result<Self> {
95        let (id, appdata) = match value.split_once(' ') {
96            Some((id, appdata)) => (id, Some(appdata)),
97            None => (value, None),
98        };
99        if !is_msid_token(id) || !appdata.is_none_or(is_msid_token) {
100            return Err(syntax("a=msid", value));
101        }
102        Ok(Msid {
103            id: id.to_owned(),
104            appdata: appdata.map(str::to_owned),
105        })
106    }
107}
108
109impl fmt::Display for Msid {
110    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
111        f.write_str(&self.id)?;
112        if let Some(appdata) = &self.appdata {
113            write!(f, " {appdata}")?;
114        }
115        Ok(())
116    }
117}
118
119/// `a=msid-semantic:<semantic> *(SP <msid-id>)`.
120///
121/// draft-ietf-mmusic-msid defined it and RFC 8830 dropped it, but browsers still write
122/// `a=msid-semantic: WMS` (Chrome, with a space after the colon) or
123/// `a=msid-semantic:WMS *` (Firefox). One leading space is accepted for that reason; the
124/// ids are tokens, or `*` for "all".
125#[derive(Debug, Clone, PartialEq, Eq)]
126pub struct MsidSemantic {
127    /// The semantic token: `WMS` for WebRTC MediaStreams.
128    pub semantic: String,
129    /// The MediaStream ids the semantic applies to; `*` stands for all of them.
130    pub ids: Vec<String>,
131}
132
133impl TypedAttribute for MsidSemantic {
134    const NAME: &'static str = "msid-semantic";
135
136    fn parse(value: &str) -> Result<Self> {
137        let mut fields =
138            grammar::fields("a=msid-semantic", value.strip_prefix(' ').unwrap_or(value))?
139                .into_iter();
140        let semantic = fields.next().unwrap_or_default();
141        let ids: Vec<String> = fields.map(str::to_owned).collect();
142        if !grammar::is_token(semantic) || !ids.iter().all(|id| is_msid_token(id)) {
143            return Err(syntax("a=msid-semantic", value));
144        }
145        Ok(MsidSemantic {
146            semantic: semantic.to_owned(),
147            ids,
148        })
149    }
150}
151
152impl fmt::Display for MsidSemantic {
153    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
154        f.write_str(&self.semantic)?;
155        for id in &self.ids {
156            write!(f, " {id}")?;
157        }
158        Ok(())
159    }
160}
161
162/// A dependency type of `a=depend` (RFC 5583 section 5.2.2): `lay` (layered), `mdc`
163/// (multiple description), or another token ("dependency types MUST be defined in a
164/// Standards-Track document").
165#[derive(Debug, Clone, PartialEq, Eq)]
166pub enum DependencyType {
167    /// `lay`: Media Partitions of a layered Media Bitstream.
168    Lay,
169    /// `mdc`: part of a multi-description Media Bitstream.
170    Mdc,
171    /// Any other token.
172    Other(String),
173}
174
175impl fmt::Display for DependencyType {
176    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
177        match self {
178            Self::Lay => f.write_str("lay"),
179            Self::Mdc => f.write_str("mdc"),
180            Self::Other(token) => f.write_str(token),
181        }
182    }
183}
184
185/// One `dependent-fmt SP dependency-tag` of `a=depend` (RFC 5583 section 5.2.2): the format
186/// of this media description, its dependency type, and at most one identification tag with
187/// the formats of that media description it depends on (any of them suffices).
188#[derive(Debug, Clone, PartialEq, Eq)]
189pub struct Dependency {
190    /// `dependent-fmt`.
191    pub fmt: String,
192    /// `dependency-type`.
193    pub typ: DependencyType,
194    /// `identification-tag ":" fmt-dependency *("," fmt-dependency)`, when present.
195    pub on: Option<(String, Vec<String>)>,
196}
197
198/// `a=depend:<dependent-fmt> <dependency-tag> *(";" SP <dependent-fmt> <dependency-tag>)`
199/// (RFC 5583 section 5.2.2, the ABNF of the section's code block). "There MUST be exactly one
200/// dependency-tag indicated per dependent-fmt": a value naming a format twice is refused.
201#[derive(Debug, Clone, PartialEq, Eq)]
202pub struct Depend {
203    /// The dependencies, in order.
204    pub dependencies: Vec<Dependency>,
205}
206
207impl Depend {
208    /// The dependency of `fmt`, if the attribute names it.
209    pub fn of(&self, fmt: &str) -> Option<&Dependency> {
210        self.dependencies.iter().find(|d| d.fmt == fmt)
211    }
212}
213
214impl TypedAttribute for Depend {
215    const NAME: &'static str = "depend";
216
217    fn parse(value: &str) -> Result<Self> {
218        let mut dependencies: Vec<Dependency> = vec![];
219        for part in value.split("; ") {
220            let fields = grammar::fields("a=depend", part)?;
221            let (fmt, typ, on) = match fields.as_slice() {
222                [fmt, typ] => (*fmt, *typ, None),
223                [fmt, typ, on] => (*fmt, *typ, Some(*on)),
224                _ => return Err(syntax("a=depend", value)),
225            };
226            if !grammar::is_token(fmt) || !grammar::is_token(typ) {
227                return Err(syntax("a=depend", value));
228            }
229            let on = match on {
230                None => None,
231                Some(on) => {
232                    let (mid, fmts) = on
233                        .split_once(':')
234                        .ok_or_else(|| syntax("a=depend", value))?;
235                    let fmts: Vec<String> = fmts.split(',').map(str::to_owned).collect();
236                    if !grammar::is_token(mid) || !fmts.iter().all(|f| grammar::is_token(f)) {
237                        return Err(syntax("a=depend", value));
238                    }
239                    Some((mid.to_owned(), fmts))
240                }
241            };
242            if dependencies.iter().any(|d| d.fmt == fmt) {
243                return Err(syntax("a=depend", value));
244            }
245            dependencies.push(Dependency {
246                fmt: fmt.to_owned(),
247                typ: match typ {
248                    "lay" => DependencyType::Lay,
249                    "mdc" => DependencyType::Mdc,
250                    other => DependencyType::Other(other.to_owned()),
251                },
252                on,
253            });
254        }
255        Ok(Depend { dependencies })
256    }
257}
258
259impl fmt::Display for Depend {
260    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
261        for (i, d) in self.dependencies.iter().enumerate() {
262            if i > 0 {
263                f.write_str("; ")?;
264            }
265            write!(f, "{} {}", d.fmt, d.typ)?;
266            if let Some((mid, fmts)) = &d.on {
267                write!(f, " {mid}:{}", fmts.join(","))?;
268            }
269        }
270        Ok(())
271    }
272}