Documentation
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
//! [SDP Attributes](https://tools.ietf.org/html/rfc4566#section-6) aka lines that start with `a=`

use derive_into_owned::IntoOwned;
use enum_as_inner::EnumAsInner;
use nom::{
    branch::alt,
    bytes::complete::{is_not, tag},
    combinator::map,
    sequence::{preceded, separated_pair, tuple},
    IResult,
};

use std::borrow::Cow;

pub mod candidate;
pub mod dtls;
pub mod extmap;
pub mod ice;
pub mod rtcp;
pub mod rtpmap;
pub mod ssrc;

use crate::parsers::*;
#[cfg(test)]
use crate::{assert_line, assert_line_print};

pub use bundle::*;
pub use candidate::*;
pub use control::*;
pub use direction::*;
pub use fingerprint::*;
pub use fmtp::*;
pub use ice::*;
pub use rtcp_option::*;
pub use rtp::*;
pub use ssrc::*;

#[derive(Clone, IntoOwned, EnumAsInner, PartialEq, Eq)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(
    feature = "serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(rename_all = "camelCase")
)]
#[non_exhaustive]
pub enum AttributeLine<'a> {
    /// `a=candidate:1853887674 2 udp 1518280447 0.0.0.0 36768 typ srflx raddr 192.168.0.196 rport 36768 generation 0`
    Candidate(candidate::Candidate<'a>),
    Ice(ice::IceParameter<'a>),
    Mid(mid::Mid<'a>),
    MsidSemantic(msid::MsidSemantic<'a>),
    Msid(msid::Msid<'a>),
    RtpMap(rtpmap::RtpMap<'a>),
    PTime(rtpmap::PTime),
    Ssrc(Ssrc<'a>),
    BundleGroup(BundleGroup<'a>),
    SsrcGroup(SsrcGroup),
    Fingerprint(Fingerprint<'a>),
    Direction(Direction),
    Rtp(Rtp<'a>),
    Rtcp(rtcp::Rtcp),
    Fmtp(Fmtp<'a>),
    RtcpFb(rtcp::Fb<'a>),
    RtcpOption(RtcpOption),
    Control(Control<'a>),
    SetupRole(dtls::SetupRole),
    Extmap(extmap::Extmap<'a>),
    BundleOnly,
    EoC,
    KeyValue {
        key: Cow<'a, str>,
        val: Cow<'a, str>,
    },
    KeyOnly(Cow<'a, str>),
}
pub fn attribute_line(input: &str) -> IResult<&str, AttributeLine> {
    alt((
        alt((
            map(mid::mid_line, AttributeLine::Mid),
            map(msid::msid_semantic_line, AttributeLine::MsidSemantic),
            map(msid::msid_line, AttributeLine::Msid),
            map(bundle::bundle_group_line, AttributeLine::BundleGroup),
            map(ice::ice_parameter_line, AttributeLine::Ice),
            map(ssrc::ssrc_line, AttributeLine::Ssrc),
            map(ssrc::ssrc_group_line, AttributeLine::SsrcGroup),
            map(rtpmap::rtpmap_line, AttributeLine::RtpMap),
            map(rtpmap::read_p_time, AttributeLine::PTime),
            map(fingerprint_line, AttributeLine::Fingerprint),
        )),
        alt((
            map(candidate::candidate_line, AttributeLine::Candidate),
            map(direction::direction_line, AttributeLine::Direction),
            map(extmap::extmap_line, AttributeLine::Extmap),
            map(dtls::setup_role_line, AttributeLine::SetupRole),
            map(rtp_attribute_line, AttributeLine::Rtp),
            map(rtcp::rtcp_attribute_line, AttributeLine::Rtcp),
            map(fmtp_attribute_line, AttributeLine::Fmtp),
            map(control_attribute_line, AttributeLine::Control),
            map(rtcp::rtcpfb_attribute_line, AttributeLine::RtcpFb),
            map(rtp_option_line, AttributeLine::RtcpOption),
            map(generic::key_val_attribute_line, |(key, val)| {
                AttributeLine::KeyValue { key, val }
            }),
            map(tag("a=bundle-only"), |_| AttributeLine::BundleOnly),
            map(tag("a=end-of-candidates"), |_| AttributeLine::EoC),
            map(generic::key_only_attribute_line, AttributeLine::KeyOnly),
        )),
    ))(input)
}

#[test]
fn test_attribute_line() {
    assert_line_print!(attribute_line, "a=bundle-only");
    assert_line_print!(attribute_line, "a=end-of-candidates");
    assert_line_print!(attribute_line, "a=extmap-allowed-mixed");
}

pub mod generic {
    use super::*;

    pub fn key_val_attribute_line(input: &str) -> IResult<&str, (Cow<'_, str>, Cow<'_, str>)> {
        a_line(map(
            separated_pair(
                cowify(read_non_colon_string),
                tag(":"),
                cowify(is_not("\n")),
            ),
            |(key, val)| (key, val),
        ))(input)
    }

    pub fn key_only_attribute_line(input: &str) -> IResult<&str, Cow<'_, str>> {
        a_line(cowify(is_not("\n")))(input)
    }

    #[test]
    fn test_lazy_attribute_line() {
        assert_line!(
            key_val_attribute_line,
            "a=foo:bar",
            ("foo".into(), "bar".into())
        );
        assert_line!(
            key_val_attribute_line,
            "a=fmtp:111 minptime=10; useinbandfec=1",
            ("fmtp".into(), "111 minptime=10; useinbandfec=1".into())
        );
        assert_line!(
            key_val_attribute_line,
            "a=setup:actpass",
            ("setup".into(), "actpass".into())
        );
    }
}

pub mod bundle {
    use super::*;

    /// `a=group:BUNDLE 0 1`
    #[derive(Clone, IntoOwned, PartialEq, Eq)]
    #[cfg_attr(feature = "debug", derive(Debug))]
    #[cfg_attr(
        feature = "serde",
        derive(serde::Serialize, serde::Deserialize),
        serde(rename_all = "camelCase")
    )]
    pub struct BundleGroup<'a>(pub Vec<Cow<'a, str>>);

    pub fn bundle_group_line(input: &str) -> IResult<&str, BundleGroup> {
        attribute("group", bundle_group)(input)
    }

    fn bundle_group(input: &str) -> IResult<&str, BundleGroup> {
        preceded(
            tag("BUNDLE"),
            map(wsf(space_separated_cow_strings), BundleGroup),
        )(input)
    }

    #[test]
    fn test_bundle_group_line() {
        assert_line!(
            bundle_group_line,
            "a=group:BUNDLE 0 1",
            BundleGroup(create_test_vec(&["0", "1"])),
            print
        );
        assert_line!(
            bundle_group_line,
            "a=group:BUNDLE video",
            BundleGroup(create_test_vec(&["video"])),
            print
        );
        assert_line!(
            bundle_group_line,
            "a=group:BUNDLE sdparta_0 sdparta_1 sdparta_2",
            BundleGroup(create_test_vec(&["sdparta_0", "sdparta_1", "sdparta_2"])),
            print
        );
    }
}

pub mod rtp {
    use super::*;

    // a=rtpmap:110 opus/48000/2
    #[derive(Clone, IntoOwned, PartialEq, Eq)]
    #[cfg_attr(feature = "debug", derive(Debug))]
    #[cfg_attr(
        feature = "serde",
        derive(serde::Serialize, serde::Deserialize),
        serde(rename_all = "camelCase")
    )]
    pub struct Rtp<'a> {
        pub payload: u32,
        pub codec: Cow<'a, str>,
        pub rate: u32,
        pub encoding: u32,
    }

    pub fn rtp_attribute_line(input: &str) -> IResult<&str, Rtp> {
        attribute("rtpmap", rtp_attribute)(input)
    }

    fn rtp_attribute(input: &str) -> IResult<&str, Rtp> {
        map(
            tuple((
                wsf(read_number),                   // payload
                wsf(cowify(read_non_slash_string)), // codec
                preceded(tag("/"), read_number),    // rate
                preceded(tag("/"), read_number),    // encoding
            )),
            |(payload, codec, rate, encoding)| Rtp {
                payload,
                codec,
                rate,
                encoding,
            },
        )(input)
    }

    #[test]
    fn test_rtp_attribute_line() {
        assert_line!("a=rtpmap:110 opus/48000/2", rtp_attribute_line);
    }
}

pub mod fmtp {
    use super::*;
    ///<https://tools.ietf.org/html/rfc4588#section-8.1>
    /// `a=fmtp:108 profile-level-id=24;object=23;bitrate=64000`
    #[derive(Clone, IntoOwned, PartialEq, Eq)]
    #[cfg_attr(feature = "debug", derive(Debug))]
    #[cfg_attr(
        feature = "serde",
        derive(serde::Serialize, serde::Deserialize),
        serde(rename_all = "camelCase")
    )]
    pub struct Fmtp<'a> {
        pub payload: u32,
        pub config: Cow<'a, str>,
    }

    pub fn fmtp_attribute_line(input: &str) -> IResult<&str, Fmtp> {
        attribute("fmtp", fmtp_attribute)(input)
    }

    fn fmtp_attribute(input: &str) -> IResult<&str, Fmtp> {
        map(
            tuple((
                read_number,               // payload
                cowify(wsf(is_not("\n"))), // config
            )),
            |(payload, config)| (Fmtp { payload, config }),
        )(input)
    }

    #[test]
    fn test_fmtp_attribute_line() {
        assert_line!(
            fmtp_attribute_line,
            "a=fmtp:108 profile-level-id=24;object=23;bitrate=64000",
            Fmtp {
                payload: 108,
                config: "profile-level-id=24;object=23;bitrate=64000".into(),
            },
            print
        );
        assert_line_print!(
            fmtp_attribute_line,
            "a=fmtp:111 minptime=10; useinbandfec=1"
        );
    }
}
pub mod control {
    use super::*;

    /// `a=control:streamid=0`
    #[derive(Clone, IntoOwned, PartialEq, Eq)]
    #[cfg_attr(feature = "debug", derive(Debug))]
    #[cfg_attr(
        feature = "serde",
        derive(serde::Serialize, serde::Deserialize),
        serde(rename_all = "camelCase")
    )]
    pub struct Control<'a>(pub Cow<'a, str>);

    pub fn control_attribute_line(input: &str) -> IResult<&str, Control> {
        attribute("control", control_attribute)(input)
    }

    fn control_attribute(input: &str) -> IResult<&str, Control> {
        map(cowify(read_string), Control)(input)
    }

    #[test]
    fn test_control_attribute_line() {
        assert_line_print!(control_attribute_line, "a=control:streamid=0");
    }
}
pub mod direction {
    use super::*;

    /// Direction
    ///
    /// `a=sendrecv`
    /// `a=sendonly`
    /// `a=recvonly`
    /// `a=inactive`
    #[derive(PartialEq, Eq, Clone, Copy)]
    #[cfg_attr(feature = "debug", derive(Debug))]
    #[cfg_attr(
        feature = "serde",
        derive(serde::Serialize, serde::Deserialize),
        serde(rename_all = "camelCase")
    )]
    #[non_exhaustive]
    pub enum Direction {
        SendOnly,
        SendRecv,
        RecvOnly,
        Inactive,
    }

    pub fn read_direction(input: &str) -> IResult<&str, Direction> {
        alt((
            map(tag("sendrecv"), |_| Direction::SendRecv),
            map(tag("sendonly"), |_| Direction::SendOnly),
            map(tag("recvonly"), |_| Direction::RecvOnly),
            map(tag("inactive"), |_| Direction::Inactive),
        ))(input)
    }

    /// `a=sendrecv`
    pub fn direction_line(input: &str) -> IResult<&str, Direction> {
        a_line(wsf(read_direction))(input)
    }

    #[test]
    fn test_direction_line() {
        assert_line!(read_direction, "sendrecv", Direction::SendRecv);
        assert_line!(direction_line, "a=sendrecv", Direction::SendRecv);

        assert_line!(read_direction, "sendonly", Direction::SendOnly);
        assert_line!(direction_line, "a=sendonly", Direction::SendOnly);

        assert_line!(read_direction, "recvonly", Direction::RecvOnly);
        assert_line!(direction_line, "a=recvonly", Direction::RecvOnly);

        assert_line!(read_direction, "inactive", Direction::Inactive);
        assert_line!(direction_line, "a=inactive", Direction::Inactive);
    }
}
pub mod rtcp_option {
    use super::*;

    #[derive(Clone, PartialEq, Eq)]
    #[cfg_attr(feature = "debug", derive(Debug))]
    #[cfg_attr(
        feature = "serde",
        derive(serde::Serialize, serde::Deserialize),
        serde(rename_all = "camelCase")
    )]
    #[non_exhaustive]
    pub enum RtcpOption {
        RtcpMux,
        RtcpMuxOnly,
        RtcpRsize,
    }

    pub fn rtp_option(input: &str) -> IResult<&str, RtcpOption> {
        alt((
            map(tag("rtcp-rsize"), |_| RtcpOption::RtcpRsize),
            map(tag("rtcp-mux-only"), |_| RtcpOption::RtcpMuxOnly),
            map(tag("rtcp-mux"), |_| RtcpOption::RtcpMux),
        ))(input)
    }
    pub fn rtp_option_line(input: &str) -> IResult<&str, RtcpOption> {
        a_line(rtp_option)(input)
    }

    #[test]
    fn test_read_rtp_option() {
        assert_line!(rtp_option_line, "a=rtcp-mux", RtcpOption::RtcpMux, print);
        assert_line!(
            rtp_option_line,
            "a=rtcp-mux-only",
            RtcpOption::RtcpMuxOnly,
            print
        );
        assert_line!(
            rtp_option_line,
            "a=rtcp-rsize",
            RtcpOption::RtcpRsize,
            print
        );
    }
}
pub mod fingerprint {
    use super::*;

    #[derive(Clone, IntoOwned, PartialEq, Eq)]
    #[cfg_attr(feature = "debug", derive(Debug))]
    #[cfg_attr(
        feature = "serde",
        derive(serde::Serialize, serde::Deserialize),
        serde(rename_all = "camelCase")
    )]
    pub struct Fingerprint<'a> {
        pub r#type: Cow<'a, str>,
        pub hash: Cow<'a, str>,
    }

    /// fingerprint
    pub fn fingerprint_line(input: &str) -> IResult<&str, Fingerprint> {
        attribute("fingerprint", fingerprint)(input)
    }

    /// fingerprint
    pub fn fingerprint(input: &str) -> IResult<&str, Fingerprint> {
        map(
            tuple((
                cowify(wsf(read_string)), // type
                cowify(wsf(read_string)), // hash
            )),
            |(r#type, hash)| Fingerprint { r#type, hash },
        )(input)
    }

    #[test]
    fn test_fingerprint_line() {
        assert_line_print!(
            fingerprint_line,
            "a=fingerprint:sha-256 19:E2:1C:3B:4B:9F:81:E6:B8:5C:F4:A5:A8:D8:73:04:BB:05:2F:70:9F:04:A9:0E:05:E9:26:33:E8:70:88:A2");
    }
}

pub mod mid {
    use super::*;

    #[derive(Clone, IntoOwned, PartialEq, Eq)]
    #[cfg_attr(feature = "debug", derive(Debug))]
    #[cfg_attr(
        feature = "serde",
        derive(serde::Serialize, serde::Deserialize),
        serde(rename_all = "camelCase")
    )]
    pub struct Mid<'a>(pub Cow<'a, str>);

    pub fn mid_line(input: &str) -> IResult<&str, Mid> {
        attribute("mid", mid)(input)
    }

    pub fn mid(input: &str) -> IResult<&str, Mid> {
        map(cowify(read_string), Mid)(input)
    }

    #[test]
    fn test_mid_line() {
        assert_line_print!(mid_line, "a=mid:1");
        assert_line_print!(mid_line, "a=mid:a1");
        assert_line_print!(mid_line, "a=mid:0");
        assert_line_print!(mid_line, "a=mid:audio")
    }
}

pub mod msid {
    use nom::{character::complete::multispace1, combinator::opt};

    use super::*;

    /// TODO: type this more strictly, if possible without `Vec`
    #[derive(Clone, derive_into_owned::IntoOwned, PartialEq, Eq)]
    #[cfg_attr(feature = "debug", derive(Debug))]
    #[cfg_attr(
        feature = "serde",
        derive(serde::Serialize, serde::Deserialize),
        serde(rename_all = "camelCase")
    )]
    pub struct MsidSemantic<'a> {
        pub semantic: Cow<'a, str>,
        pub token: Option<Cow<'a, str>>,
    }

    pub fn msid_semantic_line(input: &str) -> IResult<&str, MsidSemantic> {
        attribute("msid-semantic", msid_semantic)(input)
    }

    pub fn msid_semantic(input: &str) -> IResult<&str, MsidSemantic> {
        wsf(map(
            tuple((cowify(read_string), multispace1, opt(cowify(read_string)))),
            |(semantic, _, token)| MsidSemantic { semantic, token },
        ))(input)
    }

    #[test]
    fn test_msid_semantic_line() {
        assert_line!(
            msid_semantic_line,
            "a=msid-semantic: WMS lgsCFqt9kN2fVKw5wg3NKqGdATQoltEwOdMS",
            MsidSemantic {
                semantic: Cow::Borrowed("WMS"),
                token: Some(Cow::Borrowed("lgsCFqt9kN2fVKw5wg3NKqGdATQoltEwOdMS"))
            }
        );
        assert_line_print!(
            msid_semantic_line,
            "a=msid-semantic: WMS lgsCFqt9kN2fVKw5wg3NKqGdATQoltEwOdMS"
        );
    }

    #[derive(Clone, IntoOwned, PartialEq, Eq)]
    #[cfg_attr(feature = "debug", derive(Debug))]
    #[cfg_attr(
        feature = "serde",
        derive(serde::Serialize, serde::Deserialize),
        serde(rename_all = "camelCase")
    )]
    pub struct Msid<'a>(pub Vec<Cow<'a, str>>);

    pub fn msid_line(input: &str) -> IResult<&str, Msid> {
        attribute("msid", msid)(input)
    }

    pub fn msid(input: &str) -> IResult<&str, Msid> {
        wsf(map(space_separated_cow_strings, Msid))(input)
    }

    #[test]
    fn test_msid_line() {
        assert_line!(
            msid_line,
            "a=msid:47017fee-b6c1-4162-929c-a25110252400 f83006c5-a0ff-4e0a-9ed9-d3e6747be7d9",
            Msid(vec![
                "47017fee-b6c1-4162-929c-a25110252400".into(),
                "f83006c5-a0ff-4e0a-9ed9-d3e6747be7d9".into()
            ]),
            print
        );
        assert_line_print!(
            msid_line,
            "a=msid:61317484-2ed4-49d7-9eb7-1414322a7aae f30bdb4a-5db8-49b5-bcdc-e0c9a23172e0"
        );
    }
}