Skip to main content

rtci_sdp/description/
common.rs

1//! Fields shared by session and media descriptions.
2//!
3//! `c=` connection data ([`ConnectionInformation`](crate::description::common::ConnectionInformation), [`Address`](crate::description::common::Address)), `b=` bandwidth
4//! ([`Bandwidth`](crate::description::common::Bandwidth)) and `a=` attributes ([`Attribute`](crate::description::common::Attribute)) may appear at either level in SDP, with
5//! the media-level value overriding the session-level one — so they are modelled once here.
6//!
7//! An [`Attribute`](crate::description::common::Attribute) with no value is a flag, which is how `a=rtcp-mux` and the direction
8//! attributes are expressed.
9use std::fmt;
10
11use shared::error::Result;
12
13use super::session::ATTR_KEY_CANDIDATE;
14use crate::grammar::{self, invalid, syntax};
15
16/// Information describes the "i=" field which provides textual information
17/// about the session.
18pub type Information = String;
19
20/// ConnectionInformation defines the representation for the "c=" field
21/// containing connection data.
22#[derive(Debug, Default, Clone)]
23pub struct ConnectionInformation {
24    /// The network type, always `IN` (Internet) in practice.
25    pub network_type: String,
26    /// The address type, `IP4` or `IP6`.
27    pub address_type: String,
28    /// The connection address. The grammar requires one: the parser always sets it, and a
29    /// description built without one is not valid SDP.
30    pub address: Option<Address>,
31}
32
33impl fmt::Display for ConnectionInformation {
34    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35        if let Some(address) = &self.address {
36            write!(f, "{} {} {}", self.network_type, self.address_type, address,)
37        } else {
38            write!(f, "{} {}", self.network_type, self.address_type,)
39        }
40    }
41}
42
43impl ConnectionInformation {
44    /// Parses the value of a `c=` line: `nettype SP addrtype SP connection-address`.
45    ///
46    /// The network and address types are tokens: RFC 8866 section 5.7 lets more be
47    /// registered than `IN`, `IP4` and `IP6`, so an unknown one is kept, with its address
48    /// unchecked beyond being free of white space. For `IP4` and `IP6` the address is
49    /// checked against the grammar: a unicast address has no `/` (section 5.7: "the slash
50    /// notation ... MUST NOT be used for IP unicast addresses"), an IPv4 multicast address
51    /// has a TTL of 0 to 255, an IPv6 one has none.
52    pub fn parse(value: &str) -> Result<Self> {
53        Self::parse_fields(&grammar::fields("c=", value)?, value)
54    }
55
56    pub(crate) fn parse_fields(fields: &[&str], value: &str) -> Result<Self> {
57        let [network_type, address_type, address] = fields else {
58            return Err(syntax("c=", value));
59        };
60        if !grammar::is_token(network_type) || !grammar::is_token(address_type) {
61            return Err(syntax("c=", value));
62        }
63        Ok(ConnectionInformation {
64            network_type: (*network_type).to_owned(),
65            address_type: (*address_type).to_owned(),
66            address: Some(Address::parse(address_type, address)?),
67        })
68    }
69}
70
71/// Address describes a structured address token from within the "c=" field.
72#[derive(Debug, Default, Clone)]
73pub struct Address {
74    /// The address itself: a host name, IPv4/IPv6 literal, or multicast group.
75    pub address: String,
76    /// The multicast TTL, for multicast addresses.
77    pub ttl: Option<isize>,
78    /// The number of consecutive multicast addresses in the range.
79    pub range: Option<isize>,
80}
81
82impl fmt::Display for Address {
83    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84        write!(f, "{}", self.address)?;
85        if let Some(t) = &self.ttl {
86            write!(f, "/{t}")?;
87        }
88        if let Some(r) = &self.range {
89            write!(f, "/{r}")?;
90        }
91        Ok(())
92    }
93}
94
95impl Address {
96    /// Parses a `connection-address` of the given address type (`IP4`, `IP6`, or another
97    /// registered type, whose addresses are kept as they are).
98    pub fn parse(address_type: &str, value: &str) -> Result<Self> {
99        let plain = |address: &str| Address {
100            address: address.to_owned(),
101            ttl: None,
102            range: None,
103        };
104        let number = |what: &str, v: &str| -> Result<isize> {
105            if !grammar::is_integer(v) {
106                return Err(syntax(what, value));
107            }
108            v.parse::<u32>()
109                .map(|n| n as isize)
110                .map_err(|_| invalid(what, value))
111        };
112
113        let mut parts = value.split('/');
114        let base = parts.next().unwrap_or_default();
115        let (second, third) = (parts.next(), parts.next());
116        if parts.next().is_some() {
117            return Err(syntax("connection-address", value));
118        }
119
120        match (address_type, second, third) {
121            ("IP4", None, None) => {
122                if grammar::is_ip4_address(base) || grammar::is_fqdn(base) {
123                    Ok(plain(base))
124                } else {
125                    Err(syntax("IP4 connection-address", value))
126                }
127            }
128            ("IP4", Some(ttl), numaddr) => {
129                if !grammar::is_ip4_multicast_address(base) {
130                    return Err(syntax("IP4 multicast connection-address", value));
131                }
132                // ttl = (POS-DIGIT *2DIGIT) / "0", and section 5.7 bounds it to 0-255.
133                let ttl = grammar::digits_no_leading_zero::<u8>("multicast TTL", ttl)
134                    .map_err(|_| invalid("multicast TTL", value))?;
135                Ok(Address {
136                    address: base.to_owned(),
137                    ttl: Some(ttl as isize),
138                    range: numaddr
139                        .map(|n| number("number of addresses", n))
140                        .transpose()?,
141                })
142            }
143            ("IP6", None, None) => {
144                if grammar::is_ip6_address(base) || grammar::is_fqdn(base) {
145                    Ok(plain(base))
146                } else {
147                    Err(syntax("IP6 connection-address", value))
148                }
149            }
150            ("IP6", Some(numaddr), None) => {
151                if !grammar::is_ip6_multicast_address(base) {
152                    return Err(syntax("IP6 multicast connection-address", value));
153                }
154                Ok(Address {
155                    address: base.to_owned(),
156                    ttl: None,
157                    range: Some(number("number of addresses", numaddr)?),
158                })
159            }
160            ("IP4" | "IP6", _, _) => Err(syntax("connection-address", value)),
161            _ => {
162                if grammar::is_non_ws_string(value) {
163                    Ok(plain(value))
164                } else {
165                    Err(syntax("connection-address", value))
166                }
167            }
168        }
169    }
170}
171
172/// The bandwidth modifiers (`bwtype`) the WebRTC specifications use.
173#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
174pub enum BandwidthKind {
175    /// `CT`, conference total, in kilobits per second (RFC 8866 section 5.8).
176    ConferenceTotal,
177    /// `AS`, application specific maximum, in kilobits per second (RFC 8866 section 5.8).
178    ApplicationSpecific,
179    /// `TIAS`, transport independent application specific maximum, in bits per second
180    /// (RFC 3890).
181    Tias,
182    /// `RS`, RTCP bandwidth for active senders, in bits per second (RFC 3556).
183    RtcpSenders,
184    /// `RR`, RTCP bandwidth for receivers, in bits per second (RFC 3556).
185    RtcpReceivers,
186    /// Any other modifier. RFC 8866 section 5.8: a parser ignores it.
187    Other,
188}
189
190impl Bandwidth {
191    /// Parses the value of a `b=` line: `bwtype ":" bandwidth`, a token and digits.
192    pub fn parse(value: &str) -> Result<Self> {
193        let Some((bwtype, bandwidth)) = value.split_once(':') else {
194            return Err(syntax("b=", value));
195        };
196        if !grammar::is_token(bwtype) {
197            return Err(syntax("b=", value));
198        }
199        let bandwidth = grammar::digits::<u64>("b=", bandwidth)?;
200        let (experimental, bandwidth_type) = match bwtype.strip_prefix("X-") {
201            Some(rest) if !rest.is_empty() => (true, rest),
202            _ => (false, bwtype),
203        };
204        Ok(Bandwidth {
205            experimental,
206            bandwidth_type: bandwidth_type.to_owned(),
207            bandwidth,
208        })
209    }
210
211    /// Which modifier this line carries.
212    pub fn kind(&self) -> BandwidthKind {
213        if self.experimental {
214            return BandwidthKind::Other;
215        }
216        match self.bandwidth_type.as_str() {
217            "CT" => BandwidthKind::ConferenceTotal,
218            "AS" => BandwidthKind::ApplicationSpecific,
219            "TIAS" => BandwidthKind::Tias,
220            "RS" => BandwidthKind::RtcpSenders,
221            "RR" => BandwidthKind::RtcpReceivers,
222            _ => BandwidthKind::Other,
223        }
224    }
225
226    /// The value in bits per second: `CT` and `AS` are in kilobits per second, `TIAS`, `RS`
227    /// and `RR` in bits per second. `None` for a modifier whose unit is not known.
228    pub fn bits_per_second(&self) -> Option<u64> {
229        match self.kind() {
230            BandwidthKind::ConferenceTotal | BandwidthKind::ApplicationSpecific => {
231                Some(self.bandwidth.saturating_mul(1000))
232            }
233            BandwidthKind::Tias | BandwidthKind::RtcpSenders | BandwidthKind::RtcpReceivers => {
234                Some(self.bandwidth)
235            }
236            BandwidthKind::Other => None,
237        }
238    }
239}
240
241/// The first `b=` line of `kind` among `lines`.
242pub(crate) fn find_bandwidth(lines: &[Bandwidth], kind: BandwidthKind) -> Option<u64> {
243    lines.iter().find(|b| b.kind() == kind).map(|b| b.bandwidth)
244}
245
246/// Bandwidth describes an optional field which denotes the proposed bandwidth
247/// to be used by the session or media.
248#[derive(Debug, Default, Clone)]
249pub struct Bandwidth {
250    /// Whether the bandwidth type is experimental, written with an `X-` prefix.
251    pub experimental: bool,
252    /// The bandwidth modifier, such as `AS` (application-specific) or `CT` (conference total).
253    pub bandwidth_type: String,
254    /// The proposed bandwidth, in the unit of the modifier: kilobits per second for `CT` and
255    /// `AS`, bits per second for `TIAS`, `RS` and `RR`. See [`Bandwidth::bits_per_second`].
256    pub bandwidth: u64,
257}
258
259impl fmt::Display for Bandwidth {
260    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
261        let output = if self.experimental { "X-" } else { "" };
262        write!(f, "{}{}:{}", output, self.bandwidth_type, self.bandwidth)
263    }
264}
265
266/// EncryptionKey describes the "k=" line. RFC 8866 section 5.12 made it obsolete: it "MUST
267/// NOT be included in an SDP description and MUST be discarded if received", so the parser
268/// checks its syntax and drops it, and nothing writes one.
269pub type EncryptionKey = String;
270
271/// Attribute describes the "a=" field which represents the primary means for
272/// extending SDP.
273#[derive(Debug, Default, Clone)]
274pub struct Attribute {
275    /// The attribute name, the part before the `:`.
276    pub key: String,
277    /// The attribute value, or `None` for a flag attribute such as `a=rtcp-mux`.
278    pub value: Option<String>,
279}
280
281impl fmt::Display for Attribute {
282    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
283        if let Some(value) = &self.value {
284            write!(f, "{}:{}", self.key, value)
285        } else {
286            write!(f, "{}", self.key)
287        }
288    }
289}
290
291impl Attribute {
292    /// new constructs a new attribute
293    pub fn new(key: String, value: Option<String>) -> Self {
294        Attribute { key, value }
295    }
296
297    /// The attribute's name and value, whichever way it was built.
298    ///
299    /// A parsed attribute has its name in [`Attribute::key`] and what follows the first
300    /// colon in [`Attribute::value`]. An attribute built with the whole line as its key
301    /// (`with_property_attribute("msid:stream track")`, which prints the same line) is
302    /// split at its first colon here, so that both forms read alike.
303    pub fn parts(&self) -> (&str, Option<&str>) {
304        match &self.value {
305            Some(value) => (self.key.as_str(), Some(value.as_str())),
306            None => match self.key.split_once(':') {
307                Some((name, value)) => (name, Some(value)),
308                None => (self.key.as_str(), None),
309            },
310        }
311    }
312
313    /// is_ice_candidate returns true if the attribute key equals "candidate".
314    pub fn is_ice_candidate(&self) -> bool {
315        self.key.as_str() == ATTR_KEY_CANDIDATE
316    }
317}