1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
use std::collections::HashMap;
use std::fmt;

use url::Url;

use crate::description::common::*;
use crate::extmap::*;

/// Constants for extmap key
pub const EXT_MAP_VALUE_TRANSPORT_CC_KEY: isize = 3;
pub const EXT_MAP_VALUE_TRANSPORT_CC_URI: &str =
    "http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01";

fn ext_map_uri() -> HashMap<isize, &'static str> {
    let mut m = HashMap::new();
    m.insert(
        EXT_MAP_VALUE_TRANSPORT_CC_KEY,
        EXT_MAP_VALUE_TRANSPORT_CC_URI,
    );
    m
}

/// MediaDescription represents a media type.
/// <https://tools.ietf.org/html/rfc4566#section-5.14>
#[derive(Debug, Default, Clone)]
pub struct MediaDescription {
    /// `m=<media> <port>/<number of ports> <proto> <fmt> ...`
    ///
    /// <https://tools.ietf.org/html/rfc4566#section-5.14>
    pub media_name: MediaName,

    /// `i=<session description>`
    ///
    /// <https://tools.ietf.org/html/rfc4566#section-5.4>
    pub media_title: Option<Information>,

    /// `c=<nettype> <addrtype> <connection-address>`
    ///
    /// <https://tools.ietf.org/html/rfc4566#section-5.7>
    pub connection_information: Option<ConnectionInformation>,

    /// `b=<bwtype>:<bandwidth>`
    ///
    /// <https://tools.ietf.org/html/rfc4566#section-5.8>
    pub bandwidth: Vec<Bandwidth>,

    /// `k=<method>`
    ///
    /// `k=<method>:<encryption key>`
    ///
    /// <https://tools.ietf.org/html/rfc4566#section-5.12>
    pub encryption_key: Option<EncryptionKey>,

    /// Attributes are the primary means for extending SDP.  Attributes may
    /// be defined to be used as "session-level" attributes, "media-level"
    /// attributes, or both.
    ///
    /// <https://tools.ietf.org/html/rfc4566#section-5.12>
    pub attributes: Vec<Attribute>,
}

impl MediaDescription {
    /// attribute returns the value of an attribute and if it exists
    pub fn attribute(&self, key: &str) -> Option<Option<&str>> {
        for a in &self.attributes {
            if a.key == key {
                return Some(a.value.as_ref().map(|s| s.as_ref()));
            }
        }
        None
    }

    /// new_jsep_media_description creates a new MediaName with
    /// some settings that are required by the JSEP spec.
    pub fn new_jsep_media_description(codec_type: String, _codec_prefs: Vec<&str>) -> Self {
        MediaDescription {
            media_name: MediaName {
                media: codec_type,
                port: RangedPort {
                    value: 9,
                    range: None,
                },
                protos: vec![
                    "UDP".to_string(),
                    "TLS".to_string(),
                    "RTP".to_string(),
                    "SAVPF".to_string(),
                ],
                formats: vec![],
            },
            media_title: None,
            connection_information: Some(ConnectionInformation {
                network_type: "IN".to_string(),
                address_type: "IP4".to_string(),
                address: Some(Address {
                    address: "0.0.0.0".to_string(),
                    ttl: None,
                    range: None,
                }),
            }),
            bandwidth: vec![],
            encryption_key: None,
            attributes: vec![],
        }
    }

    /// with_property_attribute adds a property attribute 'a=key' to the media description
    pub fn with_property_attribute(mut self, key: String) -> Self {
        self.attributes.push(Attribute::new(key, None));
        self
    }

    /// with_value_attribute adds a value attribute 'a=key:value' to the media description
    pub fn with_value_attribute(mut self, key: String, value: String) -> Self {
        self.attributes.push(Attribute::new(key, Some(value)));
        self
    }

    /// with_fingerprint adds a fingerprint to the media description
    pub fn with_fingerprint(self, algorithm: String, value: String) -> Self {
        self.with_value_attribute("fingerprint".to_owned(), algorithm + " " + &value)
    }

    /// with_ice_credentials adds ICE credentials to the media description
    pub fn with_ice_credentials(self, username: String, password: String) -> Self {
        self.with_value_attribute("ice-ufrag".to_string(), username)
            .with_value_attribute("ice-pwd".to_string(), password)
    }

    /// with_codec adds codec information to the media description
    pub fn with_codec(
        mut self,
        payload_type: u8,
        name: String,
        clockrate: u32,
        channels: u16,
        fmtp: String,
    ) -> Self {
        self.media_name.formats.push(payload_type.to_string());
        let mut rtpmap = format!("{payload_type} {name}/{clockrate}");
        if channels > 0 {
            rtpmap += format!("/{channels}").as_str();
        }

        if !fmtp.is_empty() {
            self.with_value_attribute("rtpmap".to_string(), rtpmap)
                .with_value_attribute("fmtp".to_string(), format!("{payload_type} {fmtp}"))
        } else {
            self.with_value_attribute("rtpmap".to_string(), rtpmap)
        }
    }

    /// with_media_source adds media source information to the media description
    pub fn with_media_source(
        self,
        ssrc: u32,
        cname: String,
        stream_label: String,
        label: String,
    ) -> Self {
        self.
            with_value_attribute("ssrc".to_string(), format!("{ssrc} cname:{cname}")). // Deprecated but not phased out?
            with_value_attribute("ssrc".to_string(), format!("{ssrc} msid:{stream_label} {label}")).
            with_value_attribute("ssrc".to_string(), format!("{ssrc} mslabel:{stream_label}")). // Deprecated but not phased out?
            with_value_attribute("ssrc".to_string(), format!("{ssrc} label:{label}"))
        // Deprecated but not phased out?
    }

    /// with_candidate adds an ICE candidate to the media description
    /// Deprecated: use WithICECandidate instead
    pub fn with_candidate(self, value: String) -> Self {
        self.with_value_attribute("candidate".to_string(), value)
    }

    pub fn with_extmap(self, e: ExtMap) -> Self {
        self.with_property_attribute(e.marshal())
    }

    /// with_transport_cc_extmap adds an extmap to the media description
    pub fn with_transport_cc_extmap(self) -> Self {
        let uri = {
            let m = ext_map_uri();
            if let Some(uri_str) = m.get(&EXT_MAP_VALUE_TRANSPORT_CC_KEY) {
                match Url::parse(uri_str) {
                    Ok(uri) => Some(uri),
                    Err(_) => None,
                }
            } else {
                None
            }
        };

        let e = ExtMap {
            value: EXT_MAP_VALUE_TRANSPORT_CC_KEY,
            uri,
            ..Default::default()
        };

        self.with_extmap(e)
    }
}

/// RangedPort supports special format for the media field "m=" port value. If
/// it may be necessary to specify multiple transport ports, the protocol allows
/// to write it as: `<port>/<number of ports>` where number of ports is a an
/// offsetting range.
#[derive(Debug, Default, Clone)]
pub struct RangedPort {
    pub value: isize,
    pub range: Option<isize>,
}

impl fmt::Display for RangedPort {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(range) = self.range {
            write!(f, "{}/{}", self.value, range)
        } else {
            write!(f, "{}", self.value)
        }
    }
}

/// MediaName describes the "m=" field storage structure.
#[derive(Debug, Default, Clone)]
pub struct MediaName {
    pub media: String,
    pub port: RangedPort,
    pub protos: Vec<String>,
    pub formats: Vec<String>,
}

impl fmt::Display for MediaName {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = [
            self.media.clone(),
            self.port.to_string(),
            self.protos.join("/"),
            self.formats.join(" "),
        ];
        write!(f, "{}", s.join(" "))
    }
}

#[cfg(test)]
mod tests {
    use super::MediaDescription;

    #[test]
    fn test_attribute_missing() {
        let media_description = MediaDescription::default();

        assert_eq!(media_description.attribute("recvonly"), None);
    }

    #[test]
    fn test_attribute_present_with_no_value() {
        let media_description =
            MediaDescription::default().with_property_attribute("recvonly".to_owned());

        assert_eq!(media_description.attribute("recvonly"), Some(None));
    }

    #[test]
    fn test_attribute_present_with_value() {
        let media_description =
            MediaDescription::default().with_value_attribute("ptime".to_owned(), "1".to_owned());

        assert_eq!(media_description.attribute("ptime"), Some(Some("1")));
    }
}