rtci_sdp/attribute/mod.rs
1//! Typed, validated access to the attributes the WebRTC specifications use.
2//!
3//! [`SessionDescription::unmarshal`] keeps every `a=`
4//! line as a name and a value: RFC 8866 section 5.13 has an attribute that is not understood
5//! ignored, and the parser cannot know which ones its caller understands. This module is
6//! where a value gets its grammar. Each type parses the value of one attribute against the
7//! ABNF of the RFC that defines it and prints it back in the form that RFC gives.
8//!
9//! There are three ways in:
10//!
11//! * The accessors on [`SessionDescription`] and
12//! [`MediaDescription`]: `mid()`, `rtpmaps()`, `candidates()`,
13//! `fingerprints()`, `simulcast()` and so on. Each returns `Err` when the attribute is
14//! present and malformed, so a caller can tell "absent" from "broken".
15//! * The generic `typed::<T>()` / `typed_all::<T>()` for any [`TypedAttribute`](crate::attribute::TypedAttribute).
16//! * [`SessionDescription::validate`], which checks every
17//! known attribute of a description at once, together with the level each may appear at.
18//!
19//! | Attribute | Type | Defined in |
20//! |---|---|---|
21//! | `group` | [`Group`](crate::attribute::Group) | RFC 5888, RFC 9143 |
22//! | `mid` | [`Mid`](crate::attribute::Mid) | RFC 5888 |
23//! | `msid`, `msid-semantic` | [`Msid`](crate::attribute::Msid), [`MsidSemantic`](crate::attribute::MsidSemantic) | RFC 8830 |
24//! | `ssrc`, `ssrc-group` | [`Ssrc`](crate::attribute::Ssrc), [`SsrcGroup`](crate::attribute::SsrcGroup) | RFC 5576 |
25//! | `rid` | [`Rid`](crate::attribute::Rid) | RFC 8851 |
26//! | `simulcast` | [`Simulcast`](crate::attribute::Simulcast) | RFC 8853 |
27//! | `extmap` | [`ExtMap`](crate::extmap::ExtMap) | RFC 8285 |
28//! | `rtcp`, `rtcp-fb`, `rtcp-xr` | [`Rtcp`](crate::attribute::Rtcp), [`RtcpFb`](crate::attribute::RtcpFb), [`RtcpXr`](crate::attribute::RtcpXr) | RFC 3605, RFC 4585 / 5104, RFC 3611 |
29//! | `rtpmap`, `fmtp` | [`RtpMap`](crate::attribute::RtpMap), [`Fmtp`](crate::attribute::Fmtp) | RFC 8866 |
30//! | `ptime`, `maxptime`, `framerate` | [`Ptime`](crate::attribute::Ptime), [`MaxPtime`](crate::attribute::MaxPtime), [`FrameRate`](crate::attribute::FrameRate) | RFC 8866 |
31//! | `imageattr` | [`ImageAttr`](crate::attribute::ImageAttr) | RFC 6236 |
32//! | `content` | [`Content`](crate::attribute::Content) | RFC 4796 |
33//! | `candidate`, `remote-candidates` | [`Candidate`](crate::attribute::Candidate), [`RemoteCandidates`](crate::attribute::RemoteCandidates) | RFC 8839 |
34//! | `ice-ufrag`, `ice-pwd`, `ice-options`, `ice-pacing` | [`IceUfrag`](crate::attribute::IceUfrag), [`IcePwd`](crate::attribute::IcePwd), [`IceOptions`](crate::attribute::IceOptions), [`IcePacing`](crate::attribute::IcePacing) | RFC 8839 |
35//! | `fingerprint` | [`Fingerprint`](crate::attribute::Fingerprint) | RFC 8122 |
36//! | `setup` | [`Setup`](crate::attribute::Setup) | RFC 4145, RFC 8842 |
37//! | `tls-id` | [`TlsId`](crate::attribute::TlsId) | RFC 8842 |
38//! | `identity` | [`Identity`](crate::attribute::Identity) | RFC 8827 |
39//! | `sctp-port`, `max-message-size`, `sctpmap` | [`SctpPort`](crate::attribute::SctpPort), [`MaxMessageSize`](crate::attribute::MaxMessageSize), [`SctpMap`](crate::attribute::SctpMap) | RFC 8841 |
40//!
41//! Attributes without a value (`rtcp-mux`, `rtcp-mux-only`, `rtcp-rsize`, `ice-lite`,
42//! `end-of-candidates`, `bundle-only`, `extmap-allow-mixed`, `cryptex` and the four
43//! directions) are read with `flag()` or their named accessor, which refuses one that
44//! carries a value.
45//!
46//! [`mux`](crate::attribute::mux) holds the RFC 8859 multiplexing category of every attribute.
47
48use std::fmt;
49
50use shared::error::{Error, Result};
51
52use crate::description::common::Attribute;
53
54mod grouping;
55mod ice;
56pub mod mux;
57mod rtcp;
58mod rtp;
59mod sctp;
60mod security;
61mod simulcast;
62mod source;
63mod validate;
64
65#[cfg(test)]
66mod attribute_test;
67
68pub use grouping::{Depend, Dependency, DependencyType, Group, Mid, Msid, MsidSemantic};
69pub use ice::{
70 Candidate, IceOptions, IcePacing, IcePwd, IceUfrag, RemoteCandidate, RemoteCandidates,
71};
72pub use rtcp::{
73 Rtcp, RtcpAddress, RtcpFb, RtcpFbKind, RtcpFbPayloadType, RtcpXr, RtcpXrFormat, RtcpXrRttMode,
74 RtcpXrStatFlag,
75};
76pub use rtp::{
77 Content, Fmtp, FrameRate, ImageAttr, ImageAttrList, ImageAttrRange, ImageAttrSet, MaxPtime,
78 Ptime, RtpMap,
79};
80pub use sctp::{MaxMessageSize, SctpMap, SctpPort};
81pub use security::{Fingerprint, Identity, Setup, TlsId};
82pub use simulcast::{Rid, RidDirection, Simulcast, SimulcastId};
83pub use source::{Ssrc, SsrcGroup};
84pub use validate::check_attribute;
85
86/// An attribute with a value whose grammar this crate knows.
87///
88/// `parse` takes the text after `a=<name>:` and checks all of it; `Display` writes that text
89/// back in the form the defining RFC gives.
90pub trait TypedAttribute: Sized + fmt::Display {
91 /// The attribute name, as it follows `a=`.
92 const NAME: &'static str;
93
94 /// Parses the value: everything after `a=<name>:`.
95 fn parse(value: &str) -> Result<Self>;
96
97 /// The `a=` line this value makes.
98 fn to_attribute(&self) -> Attribute {
99 Attribute::new(Self::NAME.to_owned(), Some(self.to_string()))
100 }
101}
102
103fn no_value(name: &str) -> Error {
104 Error::SdpInvalidSyntax(format!("`a={name}` has no value"))
105}
106
107/// The first `a=<T::NAME>` line of `attributes`, parsed; `Ok(None)` when there is none.
108pub(crate) fn first<T: TypedAttribute>(attributes: &[Attribute]) -> Result<Option<T>> {
109 attributes
110 .iter()
111 .map(Attribute::parts)
112 .find(|(name, _)| *name == T::NAME)
113 .map(|(_, value)| T::parse(value.ok_or_else(|| no_value(T::NAME))?))
114 .transpose()
115}
116
117/// Every `a=<T::NAME>` line of `attributes`, parsed, in order. The first malformed one is
118/// the error.
119pub(crate) fn all<T: TypedAttribute>(attributes: &[Attribute]) -> Result<Vec<T>> {
120 attributes
121 .iter()
122 .map(Attribute::parts)
123 .filter(|(name, _)| *name == T::NAME)
124 .map(|(_, value)| T::parse(value.ok_or_else(|| no_value(T::NAME))?))
125 .collect()
126}
127
128/// Whether the property attribute `name` is present. One that carries a value is malformed.
129pub(crate) fn flag(attributes: &[Attribute], name: &str) -> Result<bool> {
130 match attributes
131 .iter()
132 .map(Attribute::parts)
133 .find(|(n, _)| *n == name)
134 {
135 None => Ok(false),
136 Some((_, None)) => Ok(true),
137 Some(_) => Err(Error::SdpInvalidSyntax(format!(
138 "`a={name}` takes no value"
139 ))),
140 }
141}
142
143/// A value attribute whose whole value is one checked string.
144macro_rules! string_attribute {
145 ($(#[$doc:meta])* $name:ident, $key:literal, $what:literal, |$v:ident| $check:expr) => {
146 $(#[$doc])*
147 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
148 pub struct $name(String);
149
150 impl $name {
151 /// Checks `value` against the grammar and wraps it.
152 pub fn new(value: impl Into<String>) -> shared::error::Result<Self> {
153 let value = value.into();
154 <Self as $crate::attribute::TypedAttribute>::parse(&value)
155 }
156
157 /// The value.
158 pub fn as_str(&self) -> &str {
159 &self.0
160 }
161 }
162
163 impl $crate::attribute::TypedAttribute for $name {
164 const NAME: &'static str = $key;
165
166 fn parse(value: &str) -> shared::error::Result<Self> {
167 let $v = value;
168 if $check {
169 Ok($name(value.to_owned()))
170 } else {
171 Err($crate::grammar::syntax($what, value))
172 }
173 }
174 }
175
176 impl std::fmt::Display for $name {
177 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
178 f.write_str(&self.0)
179 }
180 }
181 };
182}
183pub(crate) use string_attribute;
184
185/// The typed accessors both description levels share.
186macro_rules! common_accessors {
187 () => {
188 /// The first `a=<T::NAME>` attribute at this level, parsed. `Ok(None)` when there is
189 /// none, `Err` when it is malformed.
190 pub fn typed<T: $crate::attribute::TypedAttribute>(
191 &self,
192 ) -> shared::error::Result<Option<T>> {
193 $crate::attribute::first(&self.attributes)
194 }
195
196 /// Every `a=<T::NAME>` attribute at this level, parsed, in order.
197 pub fn typed_all<T: $crate::attribute::TypedAttribute>(
198 &self,
199 ) -> shared::error::Result<Vec<T>> {
200 $crate::attribute::all(&self.attributes)
201 }
202
203 /// Whether the property attribute `name` (one without a value, such as
204 /// `rtcp-mux`) is present at this level. `Err` when it carries a value.
205 pub fn flag(&self, name: &str) -> shared::error::Result<bool> {
206 $crate::attribute::flag(&self.attributes, name)
207 }
208
209 /// Appends the `a=` line of a typed attribute.
210 pub fn with_typed<T: $crate::attribute::TypedAttribute>(mut self, value: &T) -> Self {
211 self.attributes.push(value.to_attribute());
212 self
213 }
214
215 /// The direction attribute at this level (`sendrecv`, `sendonly`, `recvonly`,
216 /// `inactive`). `Ok(None)` when there is none; `Err` when there are several
217 /// (RFC 8866 section 6.7: at most one per level) or when one carries a value.
218 pub fn direction(&self) -> shared::error::Result<Option<$crate::direction::Direction>> {
219 let mut found = None;
220 for attribute in &self.attributes {
221 let (name, value) = attribute.parts();
222 let direction = $crate::direction::Direction::new(name);
223 if direction == $crate::direction::Direction::Unspecified {
224 continue;
225 }
226 if value.is_some() || found.is_some() {
227 return Err(shared::error::Error::SdpInvalidSyntax(format!(
228 "direction attribute `{name}`"
229 )));
230 }
231 found = Some(direction);
232 }
233 Ok(found)
234 }
235
236 /// `a=extmap` lines at this level (RFC 8285).
237 pub fn extmaps(&self) -> shared::error::Result<Vec<$crate::extmap::ExtMap>> {
238 self.typed_all()
239 }
240
241 /// Whether `a=extmap-allow-mixed` is present at this level (RFC 8285 section 6).
242 pub fn extmap_allow_mixed(&self) -> shared::error::Result<bool> {
243 self.flag($crate::description::session::ATTR_KEY_EXTMAP_ALLOW_MIXED)
244 }
245
246 /// `a=ice-ufrag` at this level (RFC 8839 section 5.4).
247 pub fn ice_ufrag(&self) -> shared::error::Result<Option<$crate::attribute::IceUfrag>> {
248 self.typed()
249 }
250
251 /// `a=ice-pwd` at this level (RFC 8839 section 5.4).
252 pub fn ice_pwd(&self) -> shared::error::Result<Option<$crate::attribute::IcePwd>> {
253 self.typed()
254 }
255
256 /// `a=ice-options` at this level (RFC 8839 section 5.6).
257 pub fn ice_options(&self) -> shared::error::Result<Option<$crate::attribute::IceOptions>> {
258 self.typed()
259 }
260
261 /// `a=fingerprint` lines at this level (RFC 8122 section 5).
262 pub fn fingerprints(&self) -> shared::error::Result<Vec<$crate::attribute::Fingerprint>> {
263 self.typed_all()
264 }
265
266 /// `a=setup` at this level (RFC 4145 section 4, RFC 8842).
267 pub fn setup(&self) -> shared::error::Result<Option<$crate::attribute::Setup>> {
268 self.typed()
269 }
270
271 /// `a=tls-id` at this level (RFC 8842 section 4).
272 pub fn tls_id(&self) -> shared::error::Result<Option<$crate::attribute::TlsId>> {
273 self.typed()
274 }
275
276 /// `a=rtcp-xr` at this level (RFC 3611 section 5.1).
277 pub fn rtcp_xr(&self) -> shared::error::Result<Option<$crate::attribute::RtcpXr>> {
278 self.typed()
279 }
280
281 /// Whether `a=cryptex` is present at this level (RFC 9335 section 4).
282 pub fn cryptex(&self) -> shared::error::Result<bool> {
283 self.flag($crate::description::session::ATTR_KEY_CRYPTEX)
284 }
285 };
286}
287pub(crate) use common_accessors;
288
289/// The typed accessors of the session level.
290macro_rules! session_accessors {
291 () => {
292 /// `a=group` lines (RFC 5888 section 5), every semantics.
293 pub fn groups(&self) -> shared::error::Result<Vec<$crate::attribute::Group>> {
294 self.typed_all()
295 }
296
297 /// The `a=group:BUNDLE` lines (RFC 9143 section 5).
298 pub fn bundle_groups(&self) -> shared::error::Result<Vec<$crate::attribute::Group>> {
299 Ok(self
300 .groups()?
301 .into_iter()
302 .filter(|g| g.is_bundle())
303 .collect())
304 }
305
306 /// Whether `a=ice-lite` is present (RFC 8839 section 5.3).
307 pub fn ice_lite(&self) -> shared::error::Result<bool> {
308 self.flag($crate::description::session::ATTR_KEY_ICELITE)
309 }
310
311 /// `a=ice-pacing` (RFC 8839 section 5.5).
312 pub fn ice_pacing(&self) -> shared::error::Result<Option<$crate::attribute::IcePacing>> {
313 self.typed()
314 }
315
316 /// `a=identity` (RFC 8827 section 5). Only the first one counts.
317 pub fn identity(&self) -> shared::error::Result<Option<$crate::attribute::Identity>> {
318 self.typed()
319 }
320
321 /// `a=msid-semantic` (draft-ietf-mmusic-msid; browsers still write it).
322 pub fn msid_semantic(
323 &self,
324 ) -> shared::error::Result<Option<$crate::attribute::MsidSemantic>> {
325 self.typed()
326 }
327 };
328}
329pub(crate) use session_accessors;
330
331/// The typed accessors of a media description.
332macro_rules! media_accessors {
333 () => {
334 /// `a=mid` (RFC 5888 section 4).
335 pub fn mid(&self) -> shared::error::Result<Option<$crate::attribute::Mid>> {
336 self.typed()
337 }
338
339 /// `a=msid` lines (RFC 8830 section 2): one per MediaStream the track is in.
340 pub fn msids(&self) -> shared::error::Result<Vec<$crate::attribute::Msid>> {
341 self.typed_all()
342 }
343
344 /// `a=ssrc` lines (RFC 5576 section 4.1), one per source attribute.
345 pub fn ssrcs(&self) -> shared::error::Result<Vec<$crate::attribute::Ssrc>> {
346 self.typed_all()
347 }
348
349 /// `a=ssrc-group` lines (RFC 5576 section 4.2).
350 pub fn ssrc_groups(&self) -> shared::error::Result<Vec<$crate::attribute::SsrcGroup>> {
351 self.typed_all()
352 }
353
354 /// `a=rid` lines (RFC 8851 section 10).
355 pub fn rids(&self) -> shared::error::Result<Vec<$crate::attribute::Rid>> {
356 self.typed_all()
357 }
358
359 /// `a=simulcast` (RFC 8853 section 5.1).
360 pub fn simulcast(&self) -> shared::error::Result<Option<$crate::attribute::Simulcast>> {
361 self.typed()
362 }
363
364 /// `a=rtcp` (RFC 3605 section 2.1).
365 pub fn rtcp(&self) -> shared::error::Result<Option<$crate::attribute::Rtcp>> {
366 self.typed()
367 }
368
369 /// Whether `a=rtcp-mux` is present (RFC 5761 section 5.1.1).
370 pub fn rtcp_mux(&self) -> shared::error::Result<bool> {
371 self.flag($crate::description::session::ATTR_KEY_RTCPMUX)
372 }
373
374 /// Whether `a=rtcp-mux-only` is present (RFC 8858 section 3).
375 pub fn rtcp_mux_only(&self) -> shared::error::Result<bool> {
376 self.flag($crate::description::session::ATTR_KEY_RTCPMUX_ONLY)
377 }
378
379 /// Whether `a=rtcp-rsize` is present (RFC 5506 section 5).
380 pub fn rtcp_rsize(&self) -> shared::error::Result<bool> {
381 self.flag($crate::description::session::ATTR_KEY_RTCPRSIZE)
382 }
383
384 /// `a=rtcp-fb` lines (RFC 4585 section 4.2), the wildcard ones included.
385 pub fn rtcp_fbs(&self) -> shared::error::Result<Vec<$crate::attribute::RtcpFb>> {
386 self.typed_all()
387 }
388
389 /// `a=rtpmap` lines (RFC 8866 section 6.6).
390 pub fn rtpmaps(&self) -> shared::error::Result<Vec<$crate::attribute::RtpMap>> {
391 self.typed_all()
392 }
393
394 /// `a=fmtp` lines (RFC 8866 section 6.15).
395 pub fn fmtps(&self) -> shared::error::Result<Vec<$crate::attribute::Fmtp>> {
396 self.typed_all()
397 }
398
399 /// `a=ptime` (RFC 8866 section 6.4).
400 pub fn ptime(&self) -> shared::error::Result<Option<$crate::attribute::Ptime>> {
401 self.typed()
402 }
403
404 /// `a=maxptime` (RFC 8866 section 6.5).
405 pub fn maxptime(&self) -> shared::error::Result<Option<$crate::attribute::MaxPtime>> {
406 self.typed()
407 }
408
409 /// `a=framerate` (RFC 8866 section 6.13).
410 pub fn framerate(&self) -> shared::error::Result<Option<$crate::attribute::FrameRate>> {
411 self.typed()
412 }
413
414 /// `a=imageattr` lines (RFC 6236 section 3.1).
415 pub fn imageattrs(&self) -> shared::error::Result<Vec<$crate::attribute::ImageAttr>> {
416 self.typed_all()
417 }
418
419 /// `a=content` (RFC 4796 section 5).
420 pub fn content(&self) -> shared::error::Result<Option<$crate::attribute::Content>> {
421 self.typed()
422 }
423
424 /// `a=candidate` lines (RFC 8839 section 5.1).
425 pub fn candidates(&self) -> shared::error::Result<Vec<$crate::attribute::Candidate>> {
426 self.typed_all()
427 }
428
429 /// Whether `a=end-of-candidates` is present (RFC 8840).
430 pub fn end_of_candidates(&self) -> shared::error::Result<bool> {
431 self.flag($crate::description::session::ATTR_KEY_END_OF_CANDIDATES)
432 }
433
434 /// `a=remote-candidates` (RFC 8839 section 5.2).
435 pub fn remote_candidates(
436 &self,
437 ) -> shared::error::Result<Option<$crate::attribute::RemoteCandidates>> {
438 self.typed()
439 }
440
441 /// `a=sctp-port` (RFC 8841 section 5).
442 pub fn sctp_port(&self) -> shared::error::Result<Option<$crate::attribute::SctpPort>> {
443 self.typed()
444 }
445
446 /// `a=max-message-size` (RFC 8841 section 6).
447 pub fn max_message_size(
448 &self,
449 ) -> shared::error::Result<Option<$crate::attribute::MaxMessageSize>> {
450 self.typed()
451 }
452
453 /// `a=sctpmap`, the form `a=sctp-port` replaced (draft-ietf-mmusic-sctp-sdp-05).
454 pub fn sctpmap(&self) -> shared::error::Result<Option<$crate::attribute::SctpMap>> {
455 self.typed()
456 }
457
458 /// Whether `a=bundle-only` is present (RFC 9143 section 6).
459 pub fn bundle_only(&self) -> shared::error::Result<bool> {
460 self.flag($crate::description::session::ATTR_KEY_BUNDLE_ONLY)
461 }
462 };
463}
464pub(crate) use media_accessors;