use std::fmt;
use shared::error::Result;
use super::session::ATTR_KEY_CANDIDATE;
use crate::grammar::{self, invalid, syntax};
pub type Information = String;
#[derive(Debug, Default, Clone)]
pub struct ConnectionInformation {
pub network_type: String,
pub address_type: String,
pub address: Option<Address>,
}
impl fmt::Display for ConnectionInformation {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Some(address) = &self.address {
write!(f, "{} {} {}", self.network_type, self.address_type, address,)
} else {
write!(f, "{} {}", self.network_type, self.address_type,)
}
}
}
impl ConnectionInformation {
pub fn parse(value: &str) -> Result<Self> {
Self::parse_fields(&grammar::fields("c=", value)?, value)
}
pub(crate) fn parse_fields(fields: &[&str], value: &str) -> Result<Self> {
let [network_type, address_type, address] = fields else {
return Err(syntax("c=", value));
};
if !grammar::is_token(network_type) || !grammar::is_token(address_type) {
return Err(syntax("c=", value));
}
Ok(ConnectionInformation {
network_type: (*network_type).to_owned(),
address_type: (*address_type).to_owned(),
address: Some(Address::parse(address_type, address)?),
})
}
}
#[derive(Debug, Default, Clone)]
pub struct Address {
pub address: String,
pub ttl: Option<isize>,
pub range: Option<isize>,
}
impl fmt::Display for Address {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.address)?;
if let Some(t) = &self.ttl {
write!(f, "/{t}")?;
}
if let Some(r) = &self.range {
write!(f, "/{r}")?;
}
Ok(())
}
}
impl Address {
pub fn parse(address_type: &str, value: &str) -> Result<Self> {
let plain = |address: &str| Address {
address: address.to_owned(),
ttl: None,
range: None,
};
let number = |what: &str, v: &str| -> Result<isize> {
if !grammar::is_integer(v) {
return Err(syntax(what, value));
}
v.parse::<u32>()
.map(|n| n as isize)
.map_err(|_| invalid(what, value))
};
let mut parts = value.split('/');
let base = parts.next().unwrap_or_default();
let (second, third) = (parts.next(), parts.next());
if parts.next().is_some() {
return Err(syntax("connection-address", value));
}
match (address_type, second, third) {
("IP4", None, None) => {
if grammar::is_ip4_address(base) || grammar::is_fqdn(base) {
Ok(plain(base))
} else {
Err(syntax("IP4 connection-address", value))
}
}
("IP4", Some(ttl), numaddr) => {
if !grammar::is_ip4_multicast_address(base) {
return Err(syntax("IP4 multicast connection-address", value));
}
let ttl = grammar::digits_no_leading_zero::<u8>("multicast TTL", ttl)
.map_err(|_| invalid("multicast TTL", value))?;
Ok(Address {
address: base.to_owned(),
ttl: Some(ttl as isize),
range: numaddr
.map(|n| number("number of addresses", n))
.transpose()?,
})
}
("IP6", None, None) => {
if grammar::is_ip6_address(base) || grammar::is_fqdn(base) {
Ok(plain(base))
} else {
Err(syntax("IP6 connection-address", value))
}
}
("IP6", Some(numaddr), None) => {
if !grammar::is_ip6_multicast_address(base) {
return Err(syntax("IP6 multicast connection-address", value));
}
Ok(Address {
address: base.to_owned(),
ttl: None,
range: Some(number("number of addresses", numaddr)?),
})
}
("IP4" | "IP6", _, _) => Err(syntax("connection-address", value)),
_ => {
if grammar::is_non_ws_string(value) {
Ok(plain(value))
} else {
Err(syntax("connection-address", value))
}
}
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum BandwidthKind {
ConferenceTotal,
ApplicationSpecific,
Tias,
RtcpSenders,
RtcpReceivers,
Other,
}
impl Bandwidth {
pub fn parse(value: &str) -> Result<Self> {
let Some((bwtype, bandwidth)) = value.split_once(':') else {
return Err(syntax("b=", value));
};
if !grammar::is_token(bwtype) {
return Err(syntax("b=", value));
}
let bandwidth = grammar::digits::<u64>("b=", bandwidth)?;
let (experimental, bandwidth_type) = match bwtype.strip_prefix("X-") {
Some(rest) if !rest.is_empty() => (true, rest),
_ => (false, bwtype),
};
Ok(Bandwidth {
experimental,
bandwidth_type: bandwidth_type.to_owned(),
bandwidth,
})
}
pub fn kind(&self) -> BandwidthKind {
if self.experimental {
return BandwidthKind::Other;
}
match self.bandwidth_type.as_str() {
"CT" => BandwidthKind::ConferenceTotal,
"AS" => BandwidthKind::ApplicationSpecific,
"TIAS" => BandwidthKind::Tias,
"RS" => BandwidthKind::RtcpSenders,
"RR" => BandwidthKind::RtcpReceivers,
_ => BandwidthKind::Other,
}
}
pub fn bits_per_second(&self) -> Option<u64> {
match self.kind() {
BandwidthKind::ConferenceTotal | BandwidthKind::ApplicationSpecific => {
Some(self.bandwidth.saturating_mul(1000))
}
BandwidthKind::Tias | BandwidthKind::RtcpSenders | BandwidthKind::RtcpReceivers => {
Some(self.bandwidth)
}
BandwidthKind::Other => None,
}
}
}
pub(crate) fn find_bandwidth(lines: &[Bandwidth], kind: BandwidthKind) -> Option<u64> {
lines.iter().find(|b| b.kind() == kind).map(|b| b.bandwidth)
}
#[derive(Debug, Default, Clone)]
pub struct Bandwidth {
pub experimental: bool,
pub bandwidth_type: String,
pub bandwidth: u64,
}
impl fmt::Display for Bandwidth {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let output = if self.experimental { "X-" } else { "" };
write!(f, "{}{}:{}", output, self.bandwidth_type, self.bandwidth)
}
}
pub type EncryptionKey = String;
#[derive(Debug, Default, Clone)]
pub struct Attribute {
pub key: String,
pub value: Option<String>,
}
impl fmt::Display for Attribute {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Some(value) = &self.value {
write!(f, "{}:{}", self.key, value)
} else {
write!(f, "{}", self.key)
}
}
}
impl Attribute {
pub fn new(key: String, value: Option<String>) -> Self {
Attribute { key, value }
}
pub fn parts(&self) -> (&str, Option<&str>) {
match &self.value {
Some(value) => (self.key.as_str(), Some(value.as_str())),
None => match self.key.split_once(':') {
Some((name, value)) => (name, Some(value)),
None => (self.key.as_str(), None),
},
}
}
pub fn is_ice_candidate(&self) -> bool {
self.key.as_str() == ATTR_KEY_CANDIDATE
}
}