Skip to main content

rtci_sdp/description/
media.rs

1//! The `m=` media description.
2//!
3//! One [`MediaDescription`](crate::description::media::MediaDescription) is a media type, a transport port and protocol, a list of formats,
4//! and the attributes that describe them. For RTP media the formats are payload types, and
5//! [`MediaDescription::codecs`](crate::description::media::MediaDescription::codecs) assembles them into [`Codec`](crate::util::Codec)s by joining the
6//! `a=rtpmap`, `a=fmtp` and `a=rtcp-fb` attributes that belong to each.
7//!
8//! [`RangedPort`](crate::description::media::RangedPort) exists because a media section may claim consecutive ports (`<port>/<count>`),
9//! which RTP/RTCP without multiplexing needs.
10use 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
21/// Constants for extmap key
22pub const EXT_MAP_VALUE_TRANSPORT_CC_KEY: u16 = 3;
23/// The transport-wide congestion control header-extension URI.
24pub 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/// MediaDescription represents a media type.
37///
38/// ## Specifications
39///
40/// * [RFC 4566 §5.14]
41///
42/// [RFC 4566 §5.14]: https://tools.ietf.org/html/rfc4566#section-5.14
43#[derive(Debug, Default, Clone)]
44pub struct MediaDescription {
45    /// `m=<media> <port>/<number of ports> <proto> <fmt> ...`
46    ///
47    /// <https://tools.ietf.org/html/rfc4566#section-5.14>
48    pub media_name: MediaName,
49
50    /// `i=<session description>`
51    ///
52    /// <https://tools.ietf.org/html/rfc4566#section-5.4>
53    pub media_title: Option<Information>,
54
55    /// `c=<nettype> <addrtype> <connection-address>`, each of the media description's
56    /// connection lines in order: none (the session-level one applies), one, or several
57    /// (RFC 8866 section 5.7: "Multiple addresses or "c=" lines MAY be specified on a
58    /// per-media basis", for layered multicast).
59    ///
60    /// <https://www.rfc-editor.org/rfc/rfc8866#section-5.7>
61    pub connection_information: Vec<ConnectionInformation>,
62
63    /// `b=<bwtype>:<bandwidth>`
64    ///
65    /// <https://tools.ietf.org/html/rfc4566#section-5.8>
66    pub bandwidth: Vec<Bandwidth>,
67
68    /// Obsolete. RFC 8866 section 5.12: a `k=` line "MUST NOT be included in an SDP
69    /// description and MUST be discarded if received". The parser never sets this field
70    /// and nothing writes it; it is kept so that code naming it still builds.
71    pub encryption_key: Option<EncryptionKey>,
72
73    /// Attributes are the primary means for extending SDP.  Attributes may
74    /// be defined to be used as "session-level" attributes, "media-level"
75    /// attributes, or both.
76    ///
77    /// <https://tools.ietf.org/html/rfc4566#section-5.12>
78    pub attributes: Vec<Attribute>,
79}
80
81impl MediaDescription {
82    /// Returns whether an attribute exists
83    pub fn has_attribute(&self, key: &str) -> bool {
84        self.attributes.iter().any(|a| a.key == key)
85    }
86
87    /// attribute returns the value of an attribute and if it exists
88    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    /// The codecs this media section offers, keyed by payload type.
98    ///
99    /// Assembled from the `a=rtpmap`, `a=fmtp` and `a=rtcp-fb` attributes. An
100    /// `a=rtcp-fb:*` line (RFC 4585 section 4.2: "applies to all formats") adds its
101    /// feedback type to every codec of the section, in the place the line has among the
102    /// other `a=rtcp-fb` lines.
103    ///
104    /// A line that does not parse is left out, so that one bad codec line does not take
105    /// the others with it; [`MediaDescription::rtpmaps`], [`MediaDescription::fmtps`] and
106    /// [`MediaDescription::rtcp_fbs`] report such a line as an error instead.
107    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        // Feedback is applied once every codec is known: a wildcard line reaches the
136        // codecs whose rtpmap follows it too.
137        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    /// The value of the first `b=` line of `kind`, in the unit of that modifier.
169    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    /// new_jsep_media_description creates a new MediaName with
177    /// some settings that are required by the JSEP spec.
178    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    /// with_property_attribute adds a property attribute 'a=key' to the media description
211    pub fn with_property_attribute(mut self, key: String) -> Self {
212        self.attributes.push(Attribute::new(key, None));
213        self
214    }
215
216    /// with_value_attribute adds a value attribute 'a=key:value' to the media description
217    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    /// with_fingerprint adds a fingerprint to the media description
223    pub fn with_fingerprint(self, algorithm: String, value: String) -> Self {
224        self.with_value_attribute("fingerprint".to_owned(), algorithm + " " + &value)
225    }
226
227    /// with_ice_credentials adds ICE credentials to the media description
228    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    /// with_codec adds codec information to the media description
234    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    /// with_media_source adds the source attributes of one SSRC to the media description:
258    /// `a=ssrc:<ssrc> cname:<cname>` (RFC 5576 section 6.1) and
259    /// `a=ssrc:<ssrc> msid:<stream id> <track id>`.
260    ///
261    /// These are the two registered source attributes WebRTC endpoints read. The Plan B
262    /// leftovers `mslabel` and `label`, which this used to write as well, were never
263    /// registered (RFC 5576 section 4.1: source attributes are registered ones).
264    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    /// with_candidate adds an ICE candidate to the media description
279    /// Deprecated: use WithICECandidate instead
280    pub fn with_candidate(self, value: String) -> Self {
281        self.with_value_attribute("candidate".to_string(), value)
282    }
283
284    /// Appends an `a=extmap` header-extension declaration.
285    pub fn with_extmap(self, e: ExtMap) -> Self {
286        self.with_property_attribute(e.marshal())
287    }
288
289    /// with_transport_cc_extmap adds an extmap to the media description
290    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/// RangedPort supports special format for the media field "m=" port value. If
311/// it may be necessary to specify multiple transport ports, the protocol allows
312/// to write it as: `<port>/<number of ports>` where number of ports is a an
313/// offsetting range.
314#[derive(Debug, Default, Clone)]
315pub struct RangedPort {
316    /// The first port number.
317    pub value: isize,
318    /// How many consecutive ports the media uses, for `<port>/<count>` form.
319    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/// MediaName describes the "m=" field storage structure.
333#[derive(Debug, Default, Clone)]
334pub struct MediaName {
335    /// The media type: `audio`, `video`, or `application` for data channels.
336    pub media: String,
337    /// The transport port, possibly a range.
338    pub port: RangedPort,
339    /// The transport protocol tokens, such as `UDP`, `TLS`, `RTP`, `SAVPF`.
340    pub protos: Vec<String>,
341    /// The payload types (for RTP media) or format tokens this section offers.
342    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}