Skip to main content

rtci_sdp/util/
mod.rs

1#[cfg(test)]
2mod util_test;
3
4use shared::error::{Error, Result};
5
6use crate::attribute::{Fmtp, RtpMap, TypedAttribute};
7use std::collections::HashMap;
8use std::fmt;
9
10/// The `a=` line prefix.
11pub const ATTRIBUTE_KEY: &str = "a=";
12
13/// ConnectionRole indicates which of the end points should initiate the connection establishment
14#[derive(Default, Debug, Copy, Clone, PartialEq, Eq)]
15pub enum ConnectionRole {
16    #[default]
17    /// No `a=setup` attribute was present.
18    Unspecified,
19
20    /// ConnectionRoleActive indicates the endpoint will initiate an outgoing connection.
21    Active,
22
23    /// ConnectionRolePassive indicates the endpoint will accept an incoming connection.
24    Passive,
25
26    /// ConnectionRoleActpass indicates the endpoint is willing to accept an incoming connection or to initiate an outgoing connection.
27    Actpass,
28
29    /// ConnectionRoleHoldconn indicates the endpoint does not want the connection to be established for the time being.
30    Holdconn,
31}
32
33const CONNECTION_ROLE_ACTIVE_STR: &str = "active";
34const CONNECTION_ROLE_PASSIVE_STR: &str = "passive";
35const CONNECTION_ROLE_ACTPASS_STR: &str = "actpass";
36const CONNECTION_ROLE_HOLDCONN_STR: &str = "holdconn";
37
38impl fmt::Display for ConnectionRole {
39    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40        let s = match self {
41            ConnectionRole::Active => CONNECTION_ROLE_ACTIVE_STR,
42            ConnectionRole::Passive => CONNECTION_ROLE_PASSIVE_STR,
43            ConnectionRole::Actpass => CONNECTION_ROLE_ACTPASS_STR,
44            ConnectionRole::Holdconn => CONNECTION_ROLE_HOLDCONN_STR,
45            _ => "Unspecified",
46        };
47        write!(f, "{s}")
48    }
49}
50
51impl From<u8> for ConnectionRole {
52    fn from(v: u8) -> Self {
53        match v {
54            1 => ConnectionRole::Active,
55            2 => ConnectionRole::Passive,
56            3 => ConnectionRole::Actpass,
57            4 => ConnectionRole::Holdconn,
58            _ => ConnectionRole::Unspecified,
59        }
60    }
61}
62
63impl From<&str> for ConnectionRole {
64    fn from(raw: &str) -> Self {
65        match raw {
66            CONNECTION_ROLE_ACTIVE_STR => ConnectionRole::Active,
67            CONNECTION_ROLE_PASSIVE_STR => ConnectionRole::Passive,
68            CONNECTION_ROLE_ACTPASS_STR => ConnectionRole::Actpass,
69            CONNECTION_ROLE_HOLDCONN_STR => ConnectionRole::Holdconn,
70            _ => ConnectionRole::Unspecified,
71        }
72    }
73}
74
75/// https://tools.ietf.org/html/draft-ietf-rtcweb-jsep-26#section-5.2.1
76/// Session ID is recommended to be constructed by generating a 64-bit
77/// quantity with the highest bit set to zero and the remaining 63-bits
78/// being cryptographically random.
79pub(crate) fn new_session_id() -> u64 {
80    let c = u64::MAX ^ (1u64 << 63);
81    rand::random::<u64>() & c
82}
83
84// Codec represents a codec
85#[derive(Debug, Clone, Default, PartialEq, Eq)]
86/// One codec offered by a media section, assembled from its `a=rtpmap`, `a=fmtp` and
87/// `a=rtcp-fb` attributes.
88pub struct Codec {
89    /// The RTP payload type that identifies this codec in the stream.
90    pub payload_type: u8,
91    /// The encoding name, such as `VP8` or `opus`.
92    pub name: String,
93    /// The RTP clock rate in Hz.
94    pub clock_rate: u32,
95    /// Codec-specific encoding parameters — the channel count, for audio.
96    pub encoding_parameters: String,
97    /// The `a=fmtp` format parameters, verbatim.
98    pub fmtp: String,
99    /// The `a=rtcp-fb` feedback types negotiated for this codec, such as `nack` or `goog-remb`.
100    pub rtcp_feedback: Vec<String>,
101}
102
103impl fmt::Display for Codec {
104    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
105        write!(
106            f,
107            "{} {}/{}/{} ({}) [",
108            self.payload_type, self.name, self.clock_rate, self.encoding_parameters, self.fmtp,
109        )?;
110
111        let mut first = true;
112        for part in &self.rtcp_feedback {
113            if first {
114                first = false;
115                write!(f, "{part}")?;
116            } else {
117                write!(f, ", {part}")?;
118            }
119        }
120
121        write!(f, "]")
122    }
123}
124
125/// The codec an `a=rtpmap` value describes: `<payload type> <encoding name>/<clock
126/// rate>[/<encoding parameters>]` (RFC 8866 section 6.6).
127pub(crate) fn parse_rtpmap(value: &str) -> Result<Codec> {
128    let rtpmap = RtpMap::parse(value)?;
129    Ok(Codec {
130        payload_type: rtpmap.payload_type,
131        name: rtpmap.encoding_name,
132        clock_rate: rtpmap.clock_rate,
133        encoding_parameters: rtpmap.channels.map(|c| c.to_string()).unwrap_or_default(),
134        ..Default::default()
135    })
136}
137
138/// The format parameters an `a=fmtp` value carries for an RTP payload type:
139/// `<format> <format specific parameters>` (RFC 8866 section 6.15). The parameters are
140/// everything after the first space.
141pub(crate) fn parse_fmtp(value: &str) -> Result<Codec> {
142    let fmtp = Fmtp::parse(value)?;
143    let payload_type = fmtp
144        .payload_type()
145        .ok_or_else(|| Error::SdpInvalidValue(format!("fmtp format `{}`", fmtp.format)))?;
146    Ok(Codec {
147        payload_type,
148        fmtp: fmtp.parameters,
149        ..Default::default()
150    })
151}
152
153/// The most `a=rtcp-fb` values one payload type keeps. Browsers declare well under a dozen per
154/// codec; further lines (and repeats of a value already kept) are dropped, so a description
155/// can't grow a codec's feedback list without bound.
156pub(crate) const MAX_RTCP_FEEDBACK_PER_CODEC: usize = 64;
157
158pub(crate) fn merge_codecs(mut codec: Codec, codecs: &mut HashMap<u8, Codec>) {
159    if let Some(saved_codec) = codecs.get_mut(&codec.payload_type) {
160        if saved_codec.payload_type == 0 {
161            saved_codec.payload_type = codec.payload_type
162        }
163        if saved_codec.name.is_empty() {
164            saved_codec.name = codec.name
165        }
166        if saved_codec.clock_rate == 0 {
167            saved_codec.clock_rate = codec.clock_rate
168        }
169        if saved_codec.encoding_parameters.is_empty() {
170            saved_codec.encoding_parameters = codec.encoding_parameters
171        }
172        if saved_codec.fmtp.is_empty() {
173            saved_codec.fmtp = codec.fmtp
174        }
175        for feedback in codec.rtcp_feedback.drain(..) {
176            if saved_codec.rtcp_feedback.len() >= MAX_RTCP_FEEDBACK_PER_CODEC {
177                break;
178            }
179            if !saved_codec.rtcp_feedback.contains(&feedback) {
180                saved_codec.rtcp_feedback.push(feedback);
181            }
182        }
183    } else {
184        codec.rtcp_feedback.truncate(MAX_RTCP_FEEDBACK_PER_CODEC);
185        codecs.insert(codec.payload_type, codec);
186    }
187}
188
189fn equivalent_fmtp(want: &str, got: &str) -> bool {
190    let mut want_split: Vec<&str> = want.split(';').collect();
191    let mut got_split: Vec<&str> = got.split(';').collect();
192
193    if want_split.len() != got_split.len() {
194        return false;
195    }
196
197    want_split.sort_unstable();
198    got_split.sort_unstable();
199
200    for (i, &want_part) in want_split.iter().enumerate() {
201        let want_part = want_part.trim();
202        let got_part = got_split[i].trim();
203        if got_part != want_part {
204            return false;
205        }
206    }
207
208    true
209}
210
211pub(crate) fn codecs_match(wanted: &Codec, got: &Codec) -> bool {
212    if !wanted.name.is_empty() && wanted.name.to_lowercase() != got.name.to_lowercase() {
213        return false;
214    }
215    if wanted.clock_rate != 0 && wanted.clock_rate != got.clock_rate {
216        return false;
217    }
218    if !wanted.encoding_parameters.is_empty()
219        && wanted.encoding_parameters != got.encoding_parameters
220    {
221        return false;
222    }
223    if !wanted.fmtp.is_empty() && !equivalent_fmtp(&wanted.fmtp, &got.fmtp) {
224        return false;
225    }
226
227    true
228}