1use std::fmt;
10
11use shared::error::Result;
12
13use super::session::ATTR_KEY_CANDIDATE;
14use crate::grammar::{self, invalid, syntax};
15
16pub type Information = String;
19
20#[derive(Debug, Default, Clone)]
23pub struct ConnectionInformation {
24 pub network_type: String,
26 pub address_type: String,
28 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 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#[derive(Debug, Default, Clone)]
73pub struct Address {
74 pub address: String,
76 pub ttl: Option<isize>,
78 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 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
174pub enum BandwidthKind {
175 ConferenceTotal,
177 ApplicationSpecific,
179 Tias,
182 RtcpSenders,
184 RtcpReceivers,
186 Other,
188}
189
190impl Bandwidth {
191 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 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 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
241pub(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#[derive(Debug, Default, Clone)]
249pub struct Bandwidth {
250 pub experimental: bool,
252 pub bandwidth_type: String,
254 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
266pub type EncryptionKey = String;
270
271#[derive(Debug, Default, Clone)]
274pub struct Attribute {
275 pub key: String,
277 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 pub fn new(key: String, value: Option<String>) -> Self {
294 Attribute { key, value }
295 }
296
297 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 pub fn is_ice_candidate(&self) -> bool {
315 self.key.as_str() == ATTR_KEY_CANDIDATE
316 }
317}