1use std::collections::HashMap;
11use std::fmt;
12
13use url::Url;
14
15use crate::attribute::{RtcpFb, RtcpFbPayloadType, TypedAttribute};
16use crate::description::common::*;
17use crate::description::session::{ATTR_KEY_FMTP, ATTR_KEY_RTCP_FB, ATTR_KEY_RTPMAP};
18use crate::extmap::*;
19use crate::util::{Codec, merge_codecs, parse_fmtp, parse_rtpmap};
20
21pub const EXT_MAP_VALUE_TRANSPORT_CC_KEY: u16 = 3;
23pub const EXT_MAP_VALUE_TRANSPORT_CC_URI: &str =
25 "http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01";
26
27fn ext_map_uri() -> HashMap<u16, &'static str> {
28 let mut m = HashMap::new();
29 m.insert(
30 EXT_MAP_VALUE_TRANSPORT_CC_KEY,
31 EXT_MAP_VALUE_TRANSPORT_CC_URI,
32 );
33 m
34}
35
36#[derive(Debug, Default, Clone)]
44pub struct MediaDescription {
45 pub media_name: MediaName,
49
50 pub media_title: Option<Information>,
54
55 pub connection_information: Vec<ConnectionInformation>,
62
63 pub bandwidth: Vec<Bandwidth>,
67
68 pub encryption_key: Option<EncryptionKey>,
72
73 pub attributes: Vec<Attribute>,
79}
80
81impl MediaDescription {
82 pub fn has_attribute(&self, key: &str) -> bool {
84 self.attributes.iter().any(|a| a.key == key)
85 }
86
87 pub fn attribute(&self, key: &str) -> Option<Option<&str>> {
89 for a in &self.attributes {
90 if a.key == key {
91 return Some(a.value.as_ref().map(|s| s.as_ref()));
92 }
93 }
94 None
95 }
96
97 pub fn codecs(&self) -> HashMap<u8, Codec> {
108 let mut codecs: HashMap<u8, Codec> = HashMap::new();
109 let mut feedback: Vec<RtcpFb> = Vec::new();
110
111 for a in &self.attributes {
112 let (name, Some(value)) = a.parts() else {
113 continue;
114 };
115 match name {
116 ATTR_KEY_RTPMAP => {
117 if let Ok(codec) = parse_rtpmap(value) {
118 merge_codecs(codec, &mut codecs);
119 }
120 }
121 ATTR_KEY_FMTP => {
122 if let Ok(codec) = parse_fmtp(value) {
123 merge_codecs(codec, &mut codecs);
124 }
125 }
126 ATTR_KEY_RTCP_FB => {
127 if let Ok(fb) = RtcpFb::parse(value) {
128 feedback.push(fb);
129 }
130 }
131 _ => {}
132 }
133 }
134
135 for fb in &feedback {
138 let targets: Vec<u8> = match fb.payload_type {
139 RtcpFbPayloadType::PayloadType(pt) => vec![pt],
140 RtcpFbPayloadType::All => {
141 let mut all: Vec<u8> = codecs.keys().copied().collect();
142 for format in &self.media_name.formats {
143 if let Ok(pt) = format.parse::<u8>()
144 && pt <= 127
145 && !all.contains(&pt)
146 {
147 all.push(pt);
148 }
149 }
150 all
151 }
152 };
153 for payload_type in targets {
154 merge_codecs(
155 Codec {
156 payload_type,
157 rtcp_feedback: vec![fb.feedback()],
158 ..Default::default()
159 },
160 &mut codecs,
161 );
162 }
163 }
164
165 codecs
166 }
167
168 pub fn bandwidth_of(&self, kind: BandwidthKind) -> Option<u64> {
170 find_bandwidth(&self.bandwidth, kind)
171 }
172
173 crate::attribute::common_accessors!();
174 crate::attribute::media_accessors!();
175
176 pub fn new_jsep_media_description(codec_type: String, _codec_prefs: Vec<&str>) -> Self {
179 MediaDescription {
180 media_name: MediaName {
181 media: codec_type,
182 port: RangedPort {
183 value: 9,
184 range: None,
185 },
186 protos: vec![
187 "UDP".to_string(),
188 "TLS".to_string(),
189 "RTP".to_string(),
190 "SAVPF".to_string(),
191 ],
192 formats: vec![],
193 },
194 media_title: None,
195 connection_information: vec![ConnectionInformation {
196 network_type: "IN".to_string(),
197 address_type: "IP4".to_string(),
198 address: Some(Address {
199 address: "0.0.0.0".to_string(),
200 ttl: None,
201 range: None,
202 }),
203 }],
204 bandwidth: vec![],
205 encryption_key: None,
206 attributes: vec![],
207 }
208 }
209
210 pub fn with_property_attribute(mut self, key: String) -> Self {
212 self.attributes.push(Attribute::new(key, None));
213 self
214 }
215
216 pub fn with_value_attribute(mut self, key: String, value: String) -> Self {
218 self.attributes.push(Attribute::new(key, Some(value)));
219 self
220 }
221
222 pub fn with_fingerprint(self, algorithm: String, value: String) -> Self {
224 self.with_value_attribute("fingerprint".to_owned(), algorithm + " " + &value)
225 }
226
227 pub fn with_ice_credentials(self, username: String, password: String) -> Self {
229 self.with_value_attribute("ice-ufrag".to_string(), username)
230 .with_value_attribute("ice-pwd".to_string(), password)
231 }
232
233 pub fn with_codec(
235 mut self,
236 payload_type: u8,
237 name: String,
238 clockrate: u32,
239 channels: u16,
240 fmtp: String,
241 ) -> Self {
242 self.media_name.formats.push(payload_type.to_string());
243 let rtpmap = if channels > 0 {
244 format!("{payload_type} {name}/{clockrate}/{channels}")
245 } else {
246 format!("{payload_type} {name}/{clockrate}")
247 };
248
249 if !fmtp.is_empty() {
250 self.with_value_attribute("rtpmap".to_string(), rtpmap)
251 .with_value_attribute("fmtp".to_string(), format!("{payload_type} {fmtp}"))
252 } else {
253 self.with_value_attribute("rtpmap".to_string(), rtpmap)
254 }
255 }
256
257 pub fn with_media_source(
265 self,
266 ssrc: u32,
267 cname: String,
268 stream_id: String,
269 track_id: String,
270 ) -> Self {
271 self.with_value_attribute("ssrc".to_string(), format!("{ssrc} cname:{cname}"))
272 .with_value_attribute(
273 "ssrc".to_string(),
274 format!("{ssrc} msid:{stream_id} {track_id}"),
275 )
276 }
277
278 pub fn with_candidate(self, value: String) -> Self {
281 self.with_value_attribute("candidate".to_string(), value)
282 }
283
284 pub fn with_extmap(self, e: ExtMap) -> Self {
286 self.with_property_attribute(e.marshal())
287 }
288
289 pub fn with_transport_cc_extmap(self) -> Self {
291 let uri = {
292 let m = ext_map_uri();
293 if let Some(uri_str) = m.get(&EXT_MAP_VALUE_TRANSPORT_CC_KEY) {
294 Url::parse(uri_str).ok()
295 } else {
296 None
297 }
298 };
299
300 let e = ExtMap {
301 value: EXT_MAP_VALUE_TRANSPORT_CC_KEY,
302 uri,
303 ..Default::default()
304 };
305
306 self.with_extmap(e)
307 }
308}
309
310#[derive(Debug, Default, Clone)]
315pub struct RangedPort {
316 pub value: isize,
318 pub range: Option<isize>,
320}
321
322impl fmt::Display for RangedPort {
323 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
324 if let Some(range) = self.range {
325 write!(f, "{}/{}", self.value, range)
326 } else {
327 write!(f, "{}", self.value)
328 }
329 }
330}
331
332#[derive(Debug, Default, Clone)]
334pub struct MediaName {
335 pub media: String,
337 pub port: RangedPort,
339 pub protos: Vec<String>,
341 pub formats: Vec<String>,
343}
344
345impl fmt::Display for MediaName {
346 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
347 write!(f, "{} {}", self.media, self.port)?;
348
349 let mut first = true;
350 for part in &self.protos {
351 if first {
352 first = false;
353 write!(f, " {part}")?;
354 } else {
355 write!(f, "/{part}")?;
356 }
357 }
358
359 for part in &self.formats {
360 write!(f, " {part}")?;
361 }
362
363 Ok(())
364 }
365}
366
367#[cfg(test)]
368mod tests {
369 use super::MediaDescription;
370
371 #[test]
372 fn test_attribute_missing() {
373 let media_description = MediaDescription::default();
374
375 assert_eq!(media_description.attribute("recvonly"), None);
376 }
377
378 #[test]
379 fn test_attribute_present_with_no_value() {
380 let media_description =
381 MediaDescription::default().with_property_attribute("recvonly".to_owned());
382
383 assert_eq!(media_description.attribute("recvonly"), Some(None));
384 }
385
386 #[test]
387 fn test_attribute_present_with_value() {
388 let media_description =
389 MediaDescription::default().with_value_attribute("ptime".to_owned(), "1".to_owned());
390
391 assert_eq!(media_description.attribute("ptime"), Some(Some("1")));
392 }
393}