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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
//! Session and media attributes.

use std::{
    borrow::Cow,
    convert::Infallible,
    fmt::{self, Display, Formatter},
    ops::{Deref, DerefMut},
    str::FromStr,
};

use str_reader::StringReader;

use crate::ParseError;

/// SDP attribute.
#[derive(Debug, Clone)]
pub struct Attribute {
    name: String,
    value: Option<String>,
}

impl Attribute {
    /// Create a new flag-attribute (i.e. an attribute without a value).
    #[inline]
    pub fn new_flag<N>(name: N) -> Self
    where
        N: ToString,
    {
        Self {
            name: name.to_string(),
            value: None,
        }
    }

    /// Create a new attribute.
    #[inline]
    pub fn new_attribute<N, V>(name: N, value: V) -> Self
    where
        N: ToString,
        V: ToString,
    {
        Self {
            name: name.to_string(),
            value: Some(value.to_string()),
        }
    }

    /// Get attribute name.
    #[inline]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Get attribute value (if any).
    #[inline]
    pub fn value(&self) -> Option<&str> {
        self.value.as_deref()
    }
}

impl Display for Attribute {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        f.write_str(&self.name)?;

        if let Some(v) = self.value.as_ref() {
            write!(f, ":{}", v)?;
        }

        Ok(())
    }
}

impl FromStr for Attribute {
    type Err = Infallible;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let (name, value) = if let Some(colon) = s.find(':') {
            let (name, rest) = s.split_at(colon);

            let value = &rest[1..];

            (name, Some(value))
        } else {
            (s, None)
        };

        let res = Self {
            name: name.to_string(),
            value: value.map(|v| v.to_string()),
        };

        Ok(res)
    }
}

/// Collection of attributes.
#[derive(Clone)]
pub struct Attributes {
    inner: Vec<Attribute>,
}

impl Attributes {
    /// Create a new collection of attributes.
    #[inline]
    pub const fn new() -> Self {
        Self { inner: Vec::new() }
    }

    /// Find the first attribute matching a given predicate.
    #[inline]
    pub fn find<F>(&self, predicate: F) -> Option<&Attribute>
    where
        F: FnMut(&Attribute) -> bool,
    {
        self.find_all(predicate).next()
    }

    /// Find all attributes matching a given predicate.
    #[inline]
    pub fn find_all<F>(&self, predicate: F) -> PredicateMatchingIter<'_, F>
    where
        F: FnMut(&Attribute) -> bool,
    {
        PredicateMatchingIter::new(self, predicate)
    }

    /// Get the first attribute matching a given name (case sensitive).
    #[inline]
    pub fn get(&self, name: &str) -> Option<&Attribute> {
        self.find(|a| a.name() == name)
    }

    /// Get all attributes matching a given name (case sensitive).
    #[inline]
    pub fn get_all<'a>(&'a self, name: &'a str) -> NameMatchingIter<'a> {
        NameMatchingIter::new(self, name)
    }

    /// Get value of the first attribute matching a given name (case
    /// sensitive).
    #[inline]
    pub fn get_value(&self, name: &str) -> Option<&str> {
        self.get(name).and_then(|a| a.value())
    }

    /// Check if there is an attribute matching a given name (case sensitive).
    #[inline]
    pub fn contains(&self, name: &str) -> bool {
        self.get(name).is_some()
    }
}

impl Default for Attributes {
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

impl Deref for Attributes {
    type Target = Vec<Attribute>;

    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl DerefMut for Attributes {
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.inner
    }
}

/// Iterator over attributes matching a given predicate.
pub struct PredicateMatchingIter<'a, F> {
    predicate: F,
    attributes: std::slice::Iter<'a, Attribute>,
}

impl<'a, F> PredicateMatchingIter<'a, F> {
    /// Create a new iterator.
    fn new(attributes: &'a [Attribute], predicate: F) -> Self {
        Self {
            predicate,
            attributes: attributes.iter(),
        }
    }
}

impl<'a, F> Iterator for PredicateMatchingIter<'a, F>
where
    F: FnMut(&Attribute) -> bool,
{
    type Item = &'a Attribute;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        loop {
            if let Some(item) = self.attributes.next() {
                if (self.predicate)(item) {
                    return Some(item);
                }
            } else {
                return None;
            }
        }
    }
}

/// Iterator over attributes matching a given name.
pub struct NameMatchingIter<'a> {
    name: &'a str,
    attributes: std::slice::Iter<'a, Attribute>,
}

impl<'a> NameMatchingIter<'a> {
    /// Create a new iterator.
    fn new(attributes: &'a [Attribute], name: &'a str) -> Self {
        Self {
            name,
            attributes: attributes.iter(),
        }
    }
}

impl<'a> Iterator for NameMatchingIter<'a> {
    type Item = &'a Attribute;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        loop {
            if let Some(item) = self.attributes.next() {
                if item.name() == self.name {
                    return Some(item);
                }
            } else {
                return None;
            }
        }
    }
}

/// Mapping from an RTP payload type to an actual encoding.
#[derive(Clone)]
pub struct RTPMap<'a> {
    payload_type: u8,
    encoding_name: &'a str,
    clock_rate: u32,
    encoding_parameters: Option<Cow<'a, str>>,
}

impl<'a> RTPMap<'a> {
    /// Create a new rtpmap attribute value.
    #[inline]
    pub const fn new(payload_type: u8, encoding_name: &'a str, clock_rate: u32) -> Self {
        Self {
            payload_type,
            encoding_name,
            clock_rate,
            encoding_parameters: None,
        }
    }

    /// Set the encoding parameters.
    #[inline]
    pub fn with_encoding_parameters<T>(mut self, params: T) -> Self
    where
        T: ToString,
    {
        self.encoding_parameters = Some(Cow::Owned(params.to_string()));
        self
    }

    /// Get the payload type.
    #[inline]
    pub fn payload_type(&self) -> u8 {
        self.payload_type
    }

    /// Get name of the encoding.
    #[inline]
    pub fn encoding_name(&self) -> &str {
        self.encoding_name
    }

    /// Get the clock rate.
    #[inline]
    pub fn clock_rate(&self) -> u32 {
        self.clock_rate
    }

    /// Get the encoding parameters (if specified).
    #[inline]
    pub fn encoding_parameters(&self) -> Option<&str> {
        self.encoding_parameters.as_deref()
    }
}

impl<'a> Display for RTPMap<'a> {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        write!(
            f,
            "{} {}/{}",
            self.payload_type, self.encoding_name, self.clock_rate
        )?;

        if let Some(params) = self.encoding_parameters.as_ref() {
            write!(f, "/{}", params)?;
        }

        Ok(())
    }
}

impl<'a> TryFrom<&'a str> for RTPMap<'a> {
    type Error = ParseError;

    fn try_from(s: &'a str) -> Result<Self, Self::Error> {
        let mut reader = StringReader::new(s);

        let payload_type = reader.read_u8()?;

        reader.skip_whitespace();

        let encoding_name = reader.read_until(|c| c == '/');

        reader.match_char('/')?;

        let clock_rate = reader.read_until(|c| c == '/').parse()?;

        let encoding_parameters = if reader.is_empty() {
            None
        } else {
            Some(Cow::Borrowed(&reader.as_str()[1..]))
        };

        let res = Self {
            payload_type,
            encoding_name,
            clock_rate,
            encoding_parameters,
        };

        Ok(res)
    }
}

/// Format-specific parameters.
#[derive(Clone)]
pub struct FormatParameters<'a> {
    format: Cow<'a, str>,
    params: Cow<'a, str>,
}

impl<'a> FormatParameters<'a> {
    /// Create a new fmtp attribute value.
    #[inline]
    pub fn new<T, U>(format: T, parameters: U) -> Self
    where
        T: ToString,
        U: ToString,
    {
        Self {
            format: Cow::Owned(format.to_string()),
            params: Cow::Owned(parameters.to_string()),
        }
    }

    /// Get the format.
    #[inline]
    pub fn format(&self) -> &str {
        &self.format
    }

    /// Get the format parameters.
    #[inline]
    pub fn parameters(&self) -> &str {
        &self.params
    }
}

impl<'a> Display for FormatParameters<'a> {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        write!(f, "{} {}", self.format, self.params)
    }
}

impl<'a> From<&'a str> for FormatParameters<'a> {
    fn from(s: &'a str) -> Self {
        let s = s.trim();

        let (format, params) = if let Some(space) = s.find(' ') {
            let (f, r) = s.split_at(space);

            let p = &r[1..];

            (f, p)
        } else {
            (s, "")
        };

        Self {
            format: Cow::Borrowed(format),
            params: Cow::Borrowed(params),
        }
    }
}