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
10pub const ATTRIBUTE_KEY: &str = "a=";
12
13#[derive(Default, Debug, Copy, Clone, PartialEq, Eq)]
15pub enum ConnectionRole {
16 #[default]
17 Unspecified,
19
20 Active,
22
23 Passive,
25
26 Actpass,
28
29 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
75pub(crate) fn new_session_id() -> u64 {
80 let c = u64::MAX ^ (1u64 << 63);
81 rand::random::<u64>() & c
82}
83
84#[derive(Debug, Clone, Default, PartialEq, Eq)]
86pub struct Codec {
89 pub payload_type: u8,
91 pub name: String,
93 pub clock_rate: u32,
95 pub encoding_parameters: String,
97 pub fmtp: String,
99 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
125pub(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
138pub(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
153pub(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}