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
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
use std::collections::HashMap;
use std::convert::TryFrom;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use std::{fmt, io};

use url::Url;

use super::common::*;
use super::media::*;
use crate::error::{Error, Result};
use crate::lexer::*;
use crate::util::*;

/// Constants for SDP attributes used in JSEP
pub const ATTR_KEY_CANDIDATE: &str = "candidate";
pub const ATTR_KEY_END_OF_CANDIDATES: &str = "end-of-candidates";
pub const ATTR_KEY_IDENTITY: &str = "identity";
pub const ATTR_KEY_GROUP: &str = "group";
pub const ATTR_KEY_SSRC: &str = "ssrc";
pub const ATTR_KEY_SSRCGROUP: &str = "ssrc-group";
pub const ATTR_KEY_MSID: &str = "msid";
pub const ATTR_KEY_MSID_SEMANTIC: &str = "msid-semantic";
pub const ATTR_KEY_CONNECTION_SETUP: &str = "setup";
pub const ATTR_KEY_MID: &str = "mid";
pub const ATTR_KEY_ICELITE: &str = "ice-lite";
pub const ATTR_KEY_RTCPMUX: &str = "rtcp-mux";
pub const ATTR_KEY_RTCPRSIZE: &str = "rtcp-rsize";
pub const ATTR_KEY_INACTIVE: &str = "inactive";
pub const ATTR_KEY_RECV_ONLY: &str = "recvonly";
pub const ATTR_KEY_SEND_ONLY: &str = "sendonly";
pub const ATTR_KEY_SEND_RECV: &str = "sendrecv";
pub const ATTR_KEY_EXT_MAP: &str = "extmap";

/// Constants for semantic tokens used in JSEP
pub const SEMANTIC_TOKEN_LIP_SYNCHRONIZATION: &str = "LS";
pub const SEMANTIC_TOKEN_FLOW_IDENTIFICATION: &str = "FID";
pub const SEMANTIC_TOKEN_FORWARD_ERROR_CORRECTION: &str = "FEC";
pub const SEMANTIC_TOKEN_WEBRTC_MEDIA_STREAMS: &str = "WMS";

/// Version describes the value provided by the "v=" field which gives
/// the version of the Session Description Protocol.
pub type Version = isize;

/// Origin defines the structure for the "o=" field which provides the
/// originator of the session plus a session identifier and version number.
#[derive(Debug, Default, Clone)]
pub struct Origin {
    pub username: String,
    pub session_id: u64,
    pub session_version: u64,
    pub network_type: String,
    pub address_type: String,
    pub unicast_address: String,
}

impl fmt::Display for Origin {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{} {} {} {} {} {}",
            self.username,
            self.session_id,
            self.session_version,
            self.network_type,
            self.address_type,
            self.unicast_address,
        )
    }
}

impl Origin {
    pub fn new() -> Self {
        Origin {
            username: "".to_owned(),
            session_id: 0,
            session_version: 0,
            network_type: "".to_owned(),
            address_type: "".to_owned(),
            unicast_address: "".to_owned(),
        }
    }
}

/// SessionName describes a structured representations for the "s=" field
/// and is the textual session name.
pub type SessionName = String;

/// EmailAddress describes a structured representations for the "e=" line
/// which specifies email contact information for the person responsible for
/// the conference.
pub type EmailAddress = String;

/// PhoneNumber describes a structured representations for the "p=" line
/// specify phone contact information for the person responsible for the
/// conference.
pub type PhoneNumber = String;

/// TimeZone defines the structured object for "z=" line which describes
/// repeated sessions scheduling.
#[derive(Debug, Default, Clone)]
pub struct TimeZone {
    pub adjustment_time: u64,
    pub offset: i64,
}

impl fmt::Display for TimeZone {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} {}", self.adjustment_time, self.offset)
    }
}

/// TimeDescription describes "t=", "r=" fields of the session description
/// which are used to specify the start and stop times for a session as well as
/// repeat intervals and durations for the scheduled session.
#[derive(Debug, Default, Clone)]
pub struct TimeDescription {
    /// `t=<start-time> <stop-time>`
    ///
    /// <https://tools.ietf.org/html/rfc4566#section-5.9>
    pub timing: Timing,

    /// `r=<repeat interval> <active duration> <offsets from start-time>`
    ///
    /// <https://tools.ietf.org/html/rfc4566#section-5.10>
    pub repeat_times: Vec<RepeatTime>,
}

/// Timing defines the "t=" field's structured representation for the start and
/// stop times.
#[derive(Debug, Default, Clone)]
pub struct Timing {
    pub start_time: u64,
    pub stop_time: u64,
}

impl fmt::Display for Timing {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} {}", self.start_time, self.stop_time)
    }
}

/// RepeatTime describes the "r=" fields of the session description which
/// represents the intervals and durations for repeated scheduled sessions.
#[derive(Debug, Default, Clone)]
pub struct RepeatTime {
    pub interval: i64,
    pub duration: i64,
    pub offsets: Vec<i64>,
}

impl fmt::Display for RepeatTime {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut fields = vec![format!("{}", self.interval), format!("{}", self.duration)];
        for value in &self.offsets {
            fields.push(format!("{value}"));
        }
        write!(f, "{}", fields.join(" "))
    }
}

/// SessionDescription is a a well-defined format for conveying sufficient
/// information to discover and participate in a multimedia session.
#[derive(Debug, Default, Clone)]
pub struct SessionDescription {
    /// `v=0`
    ///
    /// <https://tools.ietf.org/html/rfc4566#section-5.1>
    pub version: Version,

    /// `o=<username> <sess-id> <sess-version> <nettype> <addrtype> <unicast-address>`
    ///
    /// <https://tools.ietf.org/html/rfc4566#section-5.2>
    pub origin: Origin,

    /// `s=<session name>`
    ///
    /// <https://tools.ietf.org/html/rfc4566#section-5.3>
    pub session_name: SessionName,

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

    /// `u=<uri>`
    ///
    /// <https://tools.ietf.org/html/rfc4566#section-5.5>
    pub uri: Option<Url>,

    /// `e=<email-address>`
    ///
    /// <https://tools.ietf.org/html/rfc4566#section-5.6>
    pub email_address: Option<EmailAddress>,

    /// `p=<phone-number>`
    ///
    /// <https://tools.ietf.org/html/rfc4566#section-5.6>
    pub phone_number: Option<PhoneNumber>,

    /// `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>,

    /// <https://tools.ietf.org/html/rfc4566#section-5.9>
    /// <https://tools.ietf.org/html/rfc4566#section-5.10>
    pub time_descriptions: Vec<TimeDescription>,

    /// `z=<adjustment time> <offset> <adjustment time> <offset> ...`
    ///
    /// <https://tools.ietf.org/html/rfc4566#section-5.11>
    pub time_zones: Vec<TimeZone>,

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

    /// `a=<attribute>`
    ///
    /// `a=<attribute>:<value>`
    ///
    /// <https://tools.ietf.org/html/rfc4566#section-5.13>
    pub attributes: Vec<Attribute>,

    /// <https://tools.ietf.org/html/rfc4566#section-5.14>
    pub media_descriptions: Vec<MediaDescription>,
}

/// Reset cleans the SessionDescription, and sets all fields back to their default values
impl SessionDescription {
    /// API to match draft-ietf-rtcweb-jsep
    /// Move to webrtc or its own package?

    /// NewJSEPSessionDescription creates a new SessionDescription with
    /// some settings that are required by the JSEP spec.
    pub fn new_jsep_session_description(identity: bool) -> Self {
        let d = SessionDescription {
            version: 0,
            origin: Origin {
                username: "-".to_string(),
                session_id: new_session_id(),
                session_version: SystemTime::now()
                    .duration_since(UNIX_EPOCH)
                    .unwrap_or_else(|_| Duration::from_secs(0))
                    .subsec_nanos() as u64,
                network_type: "IN".to_string(),
                address_type: "IP4".to_string(),
                unicast_address: "0.0.0.0".to_string(),
            },
            session_name: "-".to_string(),
            session_information: None,
            uri: None,
            email_address: None,
            phone_number: None,
            connection_information: None,
            bandwidth: vec![],
            time_descriptions: vec![TimeDescription {
                timing: Timing {
                    start_time: 0,
                    stop_time: 0,
                },
                repeat_times: vec![],
            }],
            time_zones: vec![],
            encryption_key: None,
            attributes: vec![], // TODO: implement trickle ICE
            media_descriptions: vec![],
        };

        if identity {
            d.with_property_attribute(ATTR_KEY_IDENTITY.to_string())
        } else {
            d
        }
    }

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

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

    /// WithFingerprint adds a fingerprint to the session description
    pub fn with_fingerprint(self, algorithm: String, value: String) -> Self {
        self.with_value_attribute("fingerprint".to_string(), algorithm + " " + value.as_str())
    }

    /// WithMedia adds a media description to the session description
    pub fn with_media(mut self, md: MediaDescription) -> Self {
        self.media_descriptions.push(md);
        self
    }

    fn build_codec_map(&self) -> HashMap<u8, Codec> {
        let mut codecs: HashMap<u8, Codec> = HashMap::new();

        for m in &self.media_descriptions {
            for a in &m.attributes {
                let attr = a.to_string();
                if attr.starts_with("rtpmap:") {
                    if let Ok(codec) = parse_rtpmap(&attr) {
                        merge_codecs(codec, &mut codecs);
                    }
                } else if attr.starts_with("fmtp:") {
                    if let Ok(codec) = parse_fmtp(&attr) {
                        merge_codecs(codec, &mut codecs);
                    }
                } else if attr.starts_with("rtcp-fb:") {
                    if let Ok(codec) = parse_rtcp_fb(&attr) {
                        merge_codecs(codec, &mut codecs);
                    }
                }
            }
        }

        codecs
    }

    /// get_codec_for_payload_type scans the SessionDescription for the given payload type and returns the codec
    pub fn get_codec_for_payload_type(&self, payload_type: u8) -> Result<Codec> {
        let codecs = self.build_codec_map();

        if let Some(codec) = codecs.get(&payload_type) {
            Ok(codec.clone())
        } else {
            Err(Error::PayloadTypeNotFound)
        }
    }

    /// get_payload_type_for_codec scans the SessionDescription for a codec that matches the provided codec
    /// as closely as possible and returns its payload type
    pub fn get_payload_type_for_codec(&self, wanted: &Codec) -> Result<u8> {
        let codecs = self.build_codec_map();

        for (payload_type, codec) in codecs.iter() {
            if codecs_match(wanted, codec) {
                return Ok(*payload_type);
            }
        }

        Err(Error::CodecNotFound)
    }

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

    /// Marshal takes a SDP struct to text
    ///
    /// <https://tools.ietf.org/html/rfc4566#section-5>
    ///
    /// Session description
    ///    v=  (protocol version)
    ///    o=  (originator and session identifier)
    ///    s=  (session name)
    ///    i=* (session information)
    ///    u=* (URI of description)
    ///    e=* (email address)
    ///    p=* (phone number)
    ///    c=* (connection information -- not required if included in
    ///         all media)
    ///    b=* (zero or more bandwidth information lines)
    ///    One or more time descriptions ("t=" and "r=" lines; see below)
    ///    z=* (time zone adjustments)
    ///    k=* (encryption key)
    ///    a=* (zero or more session attribute lines)
    ///    Zero or more media descriptions
    ///
    /// Time description
    ///    t=  (time the session is active)
    ///    r=* (zero or more repeat times)
    ///
    /// Media description, if present
    ///    m=  (media name and transport address)
    ///    i=* (media title)
    ///    c=* (connection information -- optional if included at
    ///         session level)
    ///    b=* (zero or more bandwidth information lines)
    ///    k=* (encryption key)
    ///    a=* (zero or more media attribute lines)
    pub fn marshal(&self) -> String {
        let mut result = String::new();

        result += key_value_build("v=", Some(&self.version.to_string())).as_str();
        result += key_value_build("o=", Some(&self.origin.to_string())).as_str();
        result += key_value_build("s=", Some(&self.session_name)).as_str();

        result += key_value_build("i=", self.session_information.as_ref()).as_str();

        if let Some(uri) = &self.uri {
            result += key_value_build("u=", Some(&format!("{uri}"))).as_str();
        }
        result += key_value_build("e=", self.email_address.as_ref()).as_str();
        result += key_value_build("p=", self.phone_number.as_ref()).as_str();
        if let Some(connection_information) = &self.connection_information {
            result += key_value_build("c=", Some(&connection_information.to_string())).as_str();
        }

        for bandwidth in &self.bandwidth {
            result += key_value_build("b=", Some(&bandwidth.to_string())).as_str();
        }
        for time_description in &self.time_descriptions {
            result += key_value_build("t=", Some(&time_description.timing.to_string())).as_str();
            for repeat_time in &time_description.repeat_times {
                result += key_value_build("r=", Some(&repeat_time.to_string())).as_str();
            }
        }
        if !self.time_zones.is_empty() {
            let mut time_zones = vec![];
            for time_zone in &self.time_zones {
                time_zones.push(time_zone.to_string());
            }
            result += key_value_build("z=", Some(&time_zones.join(" "))).as_str();
        }
        result += key_value_build("k=", self.encryption_key.as_ref()).as_str();
        for attribute in &self.attributes {
            result += key_value_build("a=", Some(&attribute.to_string())).as_str();
        }

        for media_description in &self.media_descriptions {
            result +=
                key_value_build("m=", Some(&media_description.media_name.to_string())).as_str();
            result += key_value_build("i=", media_description.media_title.as_ref()).as_str();
            if let Some(connection_information) = &media_description.connection_information {
                result += key_value_build("c=", Some(&connection_information.to_string())).as_str();
            }
            for bandwidth in &media_description.bandwidth {
                result += key_value_build("b=", Some(&bandwidth.to_string())).as_str();
            }
            result += key_value_build("k=", media_description.encryption_key.as_ref()).as_str();
            for attribute in &media_description.attributes {
                result += key_value_build("a=", Some(&attribute.to_string())).as_str();
            }
        }

        result
    }

    /// Unmarshal is the primary function that deserializes the session description
    /// message and stores it inside of a structured SessionDescription object.
    ///
    /// The States Transition Table describes the computation flow between functions
    /// (namely s1, s2, s3, ...) for a parsing procedure that complies with the
    /// specifications laid out by the rfc4566#section-5 as well as by JavaScript
    /// Session Establishment Protocol draft. Links:
    ///     <https://tools.ietf.org/html/rfc4566#section-5>
    ///     <https://tools.ietf.org/html/draft-ietf-rtcweb-jsep-24>
    ///
    /// <https://tools.ietf.org/html/rfc4566#section-5>
    ///
    /// Session description
    ///    v=  (protocol version)
    ///    o=  (originator and session identifier)
    ///    s=  (session name)
    ///    i=* (session information)
    ///    u=* (URI of description)
    ///    e=* (email address)
    ///    p=* (phone number)
    ///    c=* (connection information -- not required if included in
    ///         all media)
    ///    b=* (zero or more bandwidth information lines)
    ///    One or more time descriptions ("t=" and "r=" lines; see below)
    ///    z=* (time zone adjustments)
    ///    k=* (encryption key)
    ///    a=* (zero or more session attribute lines)
    ///    Zero or more media descriptions
    ///
    /// Time description
    ///    t=  (time the session is active)
    ///    r=* (zero or more repeat times)
    ///
    /// Media description, if present
    ///    m=  (media name and transport address)
    ///    i=* (media title)
    ///    c=* (connection information -- optional if included at
    ///         session level)
    ///    b=* (zero or more bandwidth information lines)
    ///    k=* (encryption key)
    ///    a=* (zero or more media attribute lines)
    ///
    /// In order to generate the following state table and draw subsequent
    /// deterministic finite-state automota ("DFA") the following regex was used to
    /// derive the DFA:
    ///    vosi?u?e?p?c?b*(tr*)+z?k?a*(mi?c?b*k?a*)*
    /// possible place and state to exit:
    ///                    **   * * *  ** * * * *
    ///                    99   1 1 1  11 1 1 1 1
    ///                         3 1 1  26 5 5 4 4
    ///
    /// Please pay close attention to the `k`, and `a` parsing states. In the table
    /// below in order to distinguish between the states belonging to the media
    /// description as opposed to the session description, the states are marked
    /// with an asterisk ("a*", "k*").
    ///
    /// ```ignore
    /// +--------+----+-------+----+-----+----+-----+---+----+----+---+---+-----+---+---+----+---+----+
    /// | STATES | a* | a*,k* | a  | a,k | b  | b,c | e | i  | m  | o | p | r,t | s | t | u  | v | z  |
    /// +--------+----+-------+----+-----+----+-----+---+----+----+---+---+-----+---+---+----+---+----+
    /// |   s1   |    |       |    |     |    |     |   |    |    |   |   |     |   |   |    | 2 |    |
    /// |   s2   |    |       |    |     |    |     |   |    |    | 3 |   |     |   |   |    |   |    |
    /// |   s3   |    |       |    |     |    |     |   |    |    |   |   |     | 4 |   |    |   |    |
    /// |   s4   |    |       |    |     |    |   5 | 6 |  7 |    |   | 8 |     |   | 9 | 10 |   |    |
    /// |   s5   |    |       |    |     |  5 |     |   |    |    |   |   |     |   | 9 |    |   |    |
    /// |   s6   |    |       |    |     |    |   5 |   |    |    |   | 8 |     |   | 9 |    |   |    |
    /// |   s7   |    |       |    |     |    |   5 | 6 |    |    |   | 8 |     |   | 9 | 10 |   |    |
    /// |   s8   |    |       |    |     |    |   5 |   |    |    |   |   |     |   | 9 |    |   |    |
    /// |   s9   |    |       |    |  11 |    |     |   |    | 12 |   |   |   9 |   |   |    |   | 13 |
    /// |   s10  |    |       |    |     |    |   5 | 6 |    |    |   | 8 |     |   | 9 |    |   |    |
    /// |   s11  |    |       | 11 |     |    |     |   |    | 12 |   |   |     |   |   |    |   |    |
    /// |   s12  |    |    14 |    |     |    |  15 |   | 16 | 12 |   |   |     |   |   |    |   |    |
    /// |   s13  |    |       |    |  11 |    |     |   |    | 12 |   |   |     |   |   |    |   |    |
    /// |   s14  | 14 |       |    |     |    |     |   |    | 12 |   |   |     |   |   |    |   |    |
    /// |   s15  |    |    14 |    |     | 15 |     |   |    | 12 |   |   |     |   |   |    |   |    |
    /// |   s16  |    |    14 |    |     |    |  15 |   |    | 12 |   |   |     |   |   |    |   |    |
    /// +--------+----+-------+----+-----+----+-----+---+----+----+---+---+-----+---+---+----+---+----+
    /// ```
    pub fn unmarshal<R: io::BufRead + io::Seek>(reader: &mut R) -> Result<Self> {
        let mut lexer = Lexer {
            desc: SessionDescription {
                version: 0,
                origin: Origin::new(),
                session_name: "".to_owned(),
                session_information: None,
                uri: None,
                email_address: None,
                phone_number: None,
                connection_information: None,
                bandwidth: vec![],
                time_descriptions: vec![],
                time_zones: vec![],
                encryption_key: None,
                attributes: vec![],
                media_descriptions: vec![],
            },
            reader,
        };

        let mut state = Some(StateFn { f: s1 });
        while let Some(s) = state {
            state = (s.f)(&mut lexer)?;
        }

        Ok(lexer.desc)
    }
}

impl From<SessionDescription> for String {
    fn from(sdp: SessionDescription) -> String {
        sdp.marshal()
    }
}

impl TryFrom<String> for SessionDescription {
    type Error = Error;
    fn try_from(sdp_string: String) -> Result<Self> {
        let mut reader = io::Cursor::new(sdp_string.as_bytes());
        let session_description = SessionDescription::unmarshal(&mut reader)?;
        Ok(session_description)
    }
}

fn s1<'a, R: io::BufRead + io::Seek>(lexer: &mut Lexer<'a, R>) -> Result<Option<StateFn<'a, R>>> {
    let (key, _) = read_type(lexer.reader)?;
    if &key == b"v=" {
        return Ok(Some(StateFn {
            f: unmarshal_protocol_version,
        }));
    }

    Err(Error::SdpInvalidSyntax(String::from_utf8(key)?))
}

fn s2<'a, R: io::BufRead + io::Seek>(lexer: &mut Lexer<'a, R>) -> Result<Option<StateFn<'a, R>>> {
    let (key, _) = read_type(lexer.reader)?;
    if &key == b"o=" {
        return Ok(Some(StateFn {
            f: unmarshal_origin,
        }));
    }

    Err(Error::SdpInvalidSyntax(String::from_utf8(key)?))
}

fn s3<'a, R: io::BufRead + io::Seek>(lexer: &mut Lexer<'a, R>) -> Result<Option<StateFn<'a, R>>> {
    let (key, _) = read_type(lexer.reader)?;
    if &key == b"s=" {
        return Ok(Some(StateFn {
            f: unmarshal_session_name,
        }));
    }

    Err(Error::SdpInvalidSyntax(String::from_utf8(key)?))
}

fn s4<'a, R: io::BufRead + io::Seek>(lexer: &mut Lexer<'a, R>) -> Result<Option<StateFn<'a, R>>> {
    let (key, _) = read_type(lexer.reader)?;
    match key.as_slice() {
        b"i=" => Ok(Some(StateFn {
            f: unmarshal_session_information,
        })),
        b"u=" => Ok(Some(StateFn { f: unmarshal_uri })),
        b"e=" => Ok(Some(StateFn { f: unmarshal_email })),
        b"p=" => Ok(Some(StateFn { f: unmarshal_phone })),
        b"c=" => Ok(Some(StateFn {
            f: unmarshal_session_connection_information,
        })),
        b"b=" => Ok(Some(StateFn {
            f: unmarshal_session_bandwidth,
        })),
        b"t=" => Ok(Some(StateFn {
            f: unmarshal_timing,
        })),
        _ => Err(Error::SdpInvalidSyntax(String::from_utf8(key)?)),
    }
}

fn s5<'a, R: io::BufRead + io::Seek>(lexer: &mut Lexer<'a, R>) -> Result<Option<StateFn<'a, R>>> {
    let (key, _) = read_type(lexer.reader)?;
    match key.as_slice() {
        b"b=" => Ok(Some(StateFn {
            f: unmarshal_session_bandwidth,
        })),
        b"t=" => Ok(Some(StateFn {
            f: unmarshal_timing,
        })),
        _ => Err(Error::SdpInvalidSyntax(String::from_utf8(key)?)),
    }
}

fn s6<'a, R: io::BufRead + io::Seek>(lexer: &mut Lexer<'a, R>) -> Result<Option<StateFn<'a, R>>> {
    let (key, _) = read_type(lexer.reader)?;
    match key.as_slice() {
        b"p=" => Ok(Some(StateFn { f: unmarshal_phone })),
        b"c=" => Ok(Some(StateFn {
            f: unmarshal_session_connection_information,
        })),
        b"b=" => Ok(Some(StateFn {
            f: unmarshal_session_bandwidth,
        })),
        b"t=" => Ok(Some(StateFn {
            f: unmarshal_timing,
        })),
        _ => Err(Error::SdpInvalidSyntax(String::from_utf8(key)?)),
    }
}

fn s7<'a, R: io::BufRead + io::Seek>(lexer: &mut Lexer<'a, R>) -> Result<Option<StateFn<'a, R>>> {
    let (key, _) = read_type(lexer.reader)?;
    match key.as_slice() {
        b"u=" => Ok(Some(StateFn { f: unmarshal_uri })),
        b"e=" => Ok(Some(StateFn { f: unmarshal_email })),
        b"p=" => Ok(Some(StateFn { f: unmarshal_phone })),
        b"c=" => Ok(Some(StateFn {
            f: unmarshal_session_connection_information,
        })),
        b"b=" => Ok(Some(StateFn {
            f: unmarshal_session_bandwidth,
        })),
        b"t=" => Ok(Some(StateFn {
            f: unmarshal_timing,
        })),
        _ => Err(Error::SdpInvalidSyntax(String::from_utf8(key)?)),
    }
}

fn s8<'a, R: io::BufRead + io::Seek>(lexer: &mut Lexer<'a, R>) -> Result<Option<StateFn<'a, R>>> {
    let (key, _) = read_type(lexer.reader)?;
    match key.as_slice() {
        b"c=" => Ok(Some(StateFn {
            f: unmarshal_session_connection_information,
        })),
        b"b=" => Ok(Some(StateFn {
            f: unmarshal_session_bandwidth,
        })),
        b"t=" => Ok(Some(StateFn {
            f: unmarshal_timing,
        })),
        _ => Err(Error::SdpInvalidSyntax(String::from_utf8(key)?)),
    }
}

fn s9<'a, R: io::BufRead + io::Seek>(lexer: &mut Lexer<'a, R>) -> Result<Option<StateFn<'a, R>>> {
    let (key, num_bytes) = read_type(lexer.reader)?;
    if key.is_empty() && num_bytes == 0 {
        return Ok(None);
    }

    match key.as_slice() {
        b"z=" => Ok(Some(StateFn {
            f: unmarshal_time_zones,
        })),
        b"k=" => Ok(Some(StateFn {
            f: unmarshal_session_encryption_key,
        })),
        b"a=" => Ok(Some(StateFn {
            f: unmarshal_session_attribute,
        })),
        b"r=" => Ok(Some(StateFn {
            f: unmarshal_repeat_times,
        })),
        b"t=" => Ok(Some(StateFn {
            f: unmarshal_timing,
        })),
        b"m=" => Ok(Some(StateFn {
            f: unmarshal_media_description,
        })),
        _ => Err(Error::SdpInvalidSyntax(String::from_utf8(key)?)),
    }
}

fn s10<'a, R: io::BufRead + io::Seek>(lexer: &mut Lexer<'a, R>) -> Result<Option<StateFn<'a, R>>> {
    let (key, _) = read_type(lexer.reader)?;
    match key.as_slice() {
        b"e=" => Ok(Some(StateFn { f: unmarshal_email })),
        b"p=" => Ok(Some(StateFn { f: unmarshal_phone })),
        b"c=" => Ok(Some(StateFn {
            f: unmarshal_session_connection_information,
        })),
        b"b=" => Ok(Some(StateFn {
            f: unmarshal_session_bandwidth,
        })),
        b"t=" => Ok(Some(StateFn {
            f: unmarshal_timing,
        })),
        _ => Err(Error::SdpInvalidSyntax(String::from_utf8(key)?)),
    }
}

fn s11<'a, R: io::BufRead + io::Seek>(lexer: &mut Lexer<'a, R>) -> Result<Option<StateFn<'a, R>>> {
    let (key, num_bytes) = read_type(lexer.reader)?;
    if key.is_empty() && num_bytes == 0 {
        return Ok(None);
    }

    match key.as_slice() {
        b"a=" => Ok(Some(StateFn {
            f: unmarshal_session_attribute,
        })),
        b"m=" => Ok(Some(StateFn {
            f: unmarshal_media_description,
        })),
        _ => Err(Error::SdpInvalidSyntax(String::from_utf8(key)?)),
    }
}

fn s12<'a, R: io::BufRead + io::Seek>(lexer: &mut Lexer<'a, R>) -> Result<Option<StateFn<'a, R>>> {
    let (key, num_bytes) = read_type(lexer.reader)?;
    if key.is_empty() && num_bytes == 0 {
        return Ok(None);
    }

    match key.as_slice() {
        b"a=" => Ok(Some(StateFn {
            f: unmarshal_media_attribute,
        })),
        b"k=" => Ok(Some(StateFn {
            f: unmarshal_media_encryption_key,
        })),
        b"b=" => Ok(Some(StateFn {
            f: unmarshal_media_bandwidth,
        })),
        b"c=" => Ok(Some(StateFn {
            f: unmarshal_media_connection_information,
        })),
        b"i=" => Ok(Some(StateFn {
            f: unmarshal_media_title,
        })),
        b"m=" => Ok(Some(StateFn {
            f: unmarshal_media_description,
        })),
        _ => Err(Error::SdpInvalidSyntax(String::from_utf8(key)?)),
    }
}

fn s13<'a, R: io::BufRead + io::Seek>(lexer: &mut Lexer<'a, R>) -> Result<Option<StateFn<'a, R>>> {
    let (key, num_bytes) = read_type(lexer.reader)?;
    if key.is_empty() && num_bytes == 0 {
        return Ok(None);
    }

    match key.as_slice() {
        b"a=" => Ok(Some(StateFn {
            f: unmarshal_session_attribute,
        })),
        b"k=" => Ok(Some(StateFn {
            f: unmarshal_session_encryption_key,
        })),
        b"m=" => Ok(Some(StateFn {
            f: unmarshal_media_description,
        })),
        _ => Err(Error::SdpInvalidSyntax(String::from_utf8(key)?)),
    }
}

fn s14<'a, R: io::BufRead + io::Seek>(lexer: &mut Lexer<'a, R>) -> Result<Option<StateFn<'a, R>>> {
    let (key, num_bytes) = read_type(lexer.reader)?;
    if key.is_empty() && num_bytes == 0 {
        return Ok(None);
    }

    match key.as_slice() {
        b"a=" => Ok(Some(StateFn {
            f: unmarshal_media_attribute,
        })),
        // Non-spec ordering
        b"k=" => Ok(Some(StateFn {
            f: unmarshal_media_encryption_key,
        })),
        // Non-spec ordering
        b"b=" => Ok(Some(StateFn {
            f: unmarshal_media_bandwidth,
        })),
        // Non-spec ordering
        b"c=" => Ok(Some(StateFn {
            f: unmarshal_media_connection_information,
        })),
        // Non-spec ordering
        b"i=" => Ok(Some(StateFn {
            f: unmarshal_media_title,
        })),
        b"m=" => Ok(Some(StateFn {
            f: unmarshal_media_description,
        })),
        _ => Err(Error::SdpInvalidSyntax(String::from_utf8(key)?)),
    }
}

fn s15<'a, R: io::BufRead + io::Seek>(lexer: &mut Lexer<'a, R>) -> Result<Option<StateFn<'a, R>>> {
    let (key, num_bytes) = read_type(lexer.reader)?;
    if key.is_empty() && num_bytes == 0 {
        return Ok(None);
    }

    match key.as_slice() {
        b"a=" => Ok(Some(StateFn {
            f: unmarshal_media_attribute,
        })),
        b"k=" => Ok(Some(StateFn {
            f: unmarshal_media_encryption_key,
        })),
        b"b=" => Ok(Some(StateFn {
            f: unmarshal_media_bandwidth,
        })),
        b"c=" => Ok(Some(StateFn {
            f: unmarshal_media_connection_information,
        })),
        // Non-spec ordering
        b"i=" => Ok(Some(StateFn {
            f: unmarshal_media_title,
        })),
        b"m=" => Ok(Some(StateFn {
            f: unmarshal_media_description,
        })),
        _ => Err(Error::SdpInvalidSyntax(String::from_utf8(key)?)),
    }
}

fn s16<'a, R: io::BufRead + io::Seek>(lexer: &mut Lexer<'a, R>) -> Result<Option<StateFn<'a, R>>> {
    let (key, num_bytes) = read_type(lexer.reader)?;
    if key.is_empty() && num_bytes == 0 {
        return Ok(None);
    }

    match key.as_slice() {
        b"a=" => Ok(Some(StateFn {
            f: unmarshal_media_attribute,
        })),
        b"k=" => Ok(Some(StateFn {
            f: unmarshal_media_encryption_key,
        })),
        b"c=" => Ok(Some(StateFn {
            f: unmarshal_media_connection_information,
        })),
        b"b=" => Ok(Some(StateFn {
            f: unmarshal_media_bandwidth,
        })),
        // Non-spec ordering
        b"i=" => Ok(Some(StateFn {
            f: unmarshal_media_title,
        })),
        b"m=" => Ok(Some(StateFn {
            f: unmarshal_media_description,
        })),
        _ => Err(Error::SdpInvalidSyntax(String::from_utf8(key)?)),
    }
}

fn unmarshal_protocol_version<'a, R: io::BufRead + io::Seek>(
    lexer: &mut Lexer<'a, R>,
) -> Result<Option<StateFn<'a, R>>> {
    let (value, _) = read_value(lexer.reader)?;

    let version = value.parse::<u32>()?;

    // As off the latest draft of the rfc this value is required to be 0.
    // https://tools.ietf.org/html/draft-ietf-rtcweb-jsep-24#section-5.8.1
    if version != 0 {
        return Err(Error::SdpInvalidSyntax(value));
    }

    Ok(Some(StateFn { f: s2 }))
}

fn unmarshal_origin<'a, R: io::BufRead + io::Seek>(
    lexer: &mut Lexer<'a, R>,
) -> Result<Option<StateFn<'a, R>>> {
    let (value, _) = read_value(lexer.reader)?;

    let fields: Vec<&str> = value.split_whitespace().collect();
    if fields.len() != 6 {
        return Err(Error::SdpInvalidSyntax(format!("`o={value}`")));
    }

    let session_id = fields[1].parse::<u64>()?;
    let session_version = fields[2].parse::<u64>()?;

    // Set according to currently registered with IANA
    // https://tools.ietf.org/html/rfc4566#section-8.2.6
    let i = index_of(fields[3], &["IN"]);
    if i == -1 {
        return Err(Error::SdpInvalidValue(fields[3].to_owned()));
    }

    // Set according to currently registered with IANA
    // https://tools.ietf.org/html/rfc4566#section-8.2.7
    let i = index_of(fields[4], &["IP4", "IP6"]);
    if i == -1 {
        return Err(Error::SdpInvalidValue(fields[4].to_owned()));
    }

    // TODO validated UnicastAddress

    lexer.desc.origin = Origin {
        username: fields[0].to_owned(),
        session_id,
        session_version,
        network_type: fields[3].to_owned(),
        address_type: fields[4].to_owned(),
        unicast_address: fields[5].to_owned(),
    };

    Ok(Some(StateFn { f: s3 }))
}

fn unmarshal_session_name<'a, R: io::BufRead + io::Seek>(
    lexer: &mut Lexer<'a, R>,
) -> Result<Option<StateFn<'a, R>>> {
    let (value, _) = read_value(lexer.reader)?;
    lexer.desc.session_name = value;
    Ok(Some(StateFn { f: s4 }))
}

fn unmarshal_session_information<'a, R: io::BufRead + io::Seek>(
    lexer: &mut Lexer<'a, R>,
) -> Result<Option<StateFn<'a, R>>> {
    let (value, _) = read_value(lexer.reader)?;
    lexer.desc.session_information = Some(value);
    Ok(Some(StateFn { f: s7 }))
}

fn unmarshal_uri<'a, R: io::BufRead + io::Seek>(
    lexer: &mut Lexer<'a, R>,
) -> Result<Option<StateFn<'a, R>>> {
    let (value, _) = read_value(lexer.reader)?;
    lexer.desc.uri = Some(Url::parse(&value)?);
    Ok(Some(StateFn { f: s10 }))
}

fn unmarshal_email<'a, R: io::BufRead + io::Seek>(
    lexer: &mut Lexer<'a, R>,
) -> Result<Option<StateFn<'a, R>>> {
    let (value, _) = read_value(lexer.reader)?;
    lexer.desc.email_address = Some(value);
    Ok(Some(StateFn { f: s6 }))
}

fn unmarshal_phone<'a, R: io::BufRead + io::Seek>(
    lexer: &mut Lexer<'a, R>,
) -> Result<Option<StateFn<'a, R>>> {
    let (value, _) = read_value(lexer.reader)?;
    lexer.desc.phone_number = Some(value);
    Ok(Some(StateFn { f: s8 }))
}

fn unmarshal_session_connection_information<'a, R: io::BufRead + io::Seek>(
    lexer: &mut Lexer<'a, R>,
) -> Result<Option<StateFn<'a, R>>> {
    let (value, _) = read_value(lexer.reader)?;
    lexer.desc.connection_information = unmarshal_connection_information(&value)?;
    Ok(Some(StateFn { f: s5 }))
}

fn unmarshal_connection_information(value: &str) -> Result<Option<ConnectionInformation>> {
    let fields: Vec<&str> = value.split_whitespace().collect();
    if fields.len() < 2 {
        return Err(Error::SdpInvalidSyntax(format!("`c={value}`")));
    }

    // Set according to currently registered with IANA
    // https://tools.ietf.org/html/rfc4566#section-8.2.6
    let i = index_of(fields[0], &["IN"]);
    if i == -1 {
        return Err(Error::SdpInvalidValue(fields[0].to_owned()));
    }

    // Set according to currently registered with IANA
    // https://tools.ietf.org/html/rfc4566#section-8.2.7
    let i = index_of(fields[1], &["IP4", "IP6"]);
    if i == -1 {
        return Err(Error::SdpInvalidValue(fields[1].to_owned()));
    }

    let address = if fields.len() > 2 {
        Some(Address {
            address: fields[2].to_owned(),
            ttl: None,
            range: None,
        })
    } else {
        None
    };

    Ok(Some(ConnectionInformation {
        network_type: fields[0].to_owned(),
        address_type: fields[1].to_owned(),
        address,
    }))
}

fn unmarshal_session_bandwidth<'a, R: io::BufRead + io::Seek>(
    lexer: &mut Lexer<'a, R>,
) -> Result<Option<StateFn<'a, R>>> {
    let (value, _) = read_value(lexer.reader)?;
    lexer.desc.bandwidth.push(unmarshal_bandwidth(&value)?);
    Ok(Some(StateFn { f: s5 }))
}

fn unmarshal_bandwidth(value: &str) -> Result<Bandwidth> {
    let mut parts: Vec<&str> = value.split(':').collect();
    if parts.len() != 2 {
        return Err(Error::SdpInvalidSyntax(format!("`b={value}`")));
    }

    let experimental = parts[0].starts_with("X-");
    if experimental {
        parts[0] = parts[0].trim_start_matches("X-");
    } else {
        // Set according to currently registered with IANA
        // https://tools.ietf.org/html/rfc4566#section-5.8 and
        // https://datatracker.ietf.org/doc/html/rfc3890
        let i = index_of(parts[0], &["CT", "AS", "TIAS"]);
        if i == -1 {
            return Err(Error::SdpInvalidValue(parts[0].to_owned()));
        }
    }

    let bandwidth = parts[1].parse::<u64>()?;

    Ok(Bandwidth {
        experimental,
        bandwidth_type: parts[0].to_owned(),
        bandwidth,
    })
}

fn unmarshal_timing<'a, R: io::BufRead + io::Seek>(
    lexer: &mut Lexer<'a, R>,
) -> Result<Option<StateFn<'a, R>>> {
    let (value, _) = read_value(lexer.reader)?;

    let fields: Vec<&str> = value.split_whitespace().collect();
    if fields.len() < 2 {
        return Err(Error::SdpInvalidSyntax(format!("`t={value}`")));
    }

    let start_time = fields[0].parse::<u64>()?;
    let stop_time = fields[1].parse::<u64>()?;

    lexer.desc.time_descriptions.push(TimeDescription {
        timing: Timing {
            start_time,
            stop_time,
        },
        repeat_times: vec![],
    });

    Ok(Some(StateFn { f: s9 }))
}

fn unmarshal_repeat_times<'a, R: io::BufRead + io::Seek>(
    lexer: &mut Lexer<'a, R>,
) -> Result<Option<StateFn<'a, R>>> {
    let (value, _) = read_value(lexer.reader)?;

    let fields: Vec<&str> = value.split_whitespace().collect();
    if fields.len() < 3 {
        return Err(Error::SdpInvalidSyntax(format!("`r={value}`")));
    }

    if let Some(latest_time_desc) = lexer.desc.time_descriptions.last_mut() {
        let interval = parse_time_units(fields[0])?;
        let duration = parse_time_units(fields[1])?;
        let mut offsets = vec![];
        for field in fields.iter().skip(2) {
            let offset = parse_time_units(field)?;
            offsets.push(offset);
        }
        latest_time_desc.repeat_times.push(RepeatTime {
            interval,
            duration,
            offsets,
        });

        Ok(Some(StateFn { f: s9 }))
    } else {
        Err(Error::SdpEmptyTimeDescription)
    }
}

fn unmarshal_time_zones<'a, R: io::BufRead + io::Seek>(
    lexer: &mut Lexer<'a, R>,
) -> Result<Option<StateFn<'a, R>>> {
    let (value, _) = read_value(lexer.reader)?;

    // These fields are transimitted in pairs
    // z=<adjustment time> <offset> <adjustment time> <offset> ....
    // so we are making sure that there are actually multiple of 2 total.
    let fields: Vec<&str> = value.split_whitespace().collect();
    if fields.len() % 2 != 0 {
        return Err(Error::SdpInvalidSyntax(format!("`t={value}`")));
    }

    for i in (0..fields.len()).step_by(2) {
        let adjustment_time = fields[i].parse::<u64>()?;
        let offset = parse_time_units(fields[i + 1])?;

        lexer.desc.time_zones.push(TimeZone {
            adjustment_time,
            offset,
        });
    }

    Ok(Some(StateFn { f: s13 }))
}

fn unmarshal_session_encryption_key<'a, R: io::BufRead + io::Seek>(
    lexer: &mut Lexer<'a, R>,
) -> Result<Option<StateFn<'a, R>>> {
    let (value, _) = read_value(lexer.reader)?;
    lexer.desc.encryption_key = Some(value);
    Ok(Some(StateFn { f: s11 }))
}

fn unmarshal_session_attribute<'a, R: io::BufRead + io::Seek>(
    lexer: &mut Lexer<'a, R>,
) -> Result<Option<StateFn<'a, R>>> {
    let (value, _) = read_value(lexer.reader)?;

    let fields: Vec<&str> = value.splitn(2, ':').collect();
    let attribute = if fields.len() == 2 {
        Attribute {
            key: fields[0].to_owned(),
            value: Some(fields[1].to_owned()),
        }
    } else {
        Attribute {
            key: fields[0].to_owned(),
            value: None,
        }
    };
    lexer.desc.attributes.push(attribute);

    Ok(Some(StateFn { f: s11 }))
}

fn unmarshal_media_description<'a, R: io::BufRead + io::Seek>(
    lexer: &mut Lexer<'a, R>,
) -> Result<Option<StateFn<'a, R>>> {
    let (value, _) = read_value(lexer.reader)?;

    let fields: Vec<&str> = value.split_whitespace().collect();
    if fields.len() < 4 {
        return Err(Error::SdpInvalidSyntax(format!("`m={value}`")));
    }

    // <media>
    // Set according to currently registered with IANA
    // https://tools.ietf.org/html/rfc4566#section-5.14
    // including "image", registered here:
    // https://datatracker.ietf.org/doc/html/rfc6466
    let i = index_of(
        fields[0],
        &["audio", "video", "text", "application", "message", "image"],
    );
    if i == -1 {
        return Err(Error::SdpInvalidValue(fields[0].to_owned()));
    }

    // <port>
    let parts: Vec<&str> = fields[1].split('/').collect();
    let port_value = parts[0].parse::<u16>()? as isize;
    let port_range = if parts.len() > 1 {
        Some(parts[1].parse::<i32>()? as isize)
    } else {
        None
    };

    // <proto>
    // Set according to currently registered with IANA
    // https://tools.ietf.org/html/rfc4566#section-5.14
    let mut protos = vec![];
    for proto in fields[2].split('/').collect::<Vec<&str>>() {
        let i = index_of(
            proto,
            &[
                "UDP", "RTP", "AVP", "SAVP", "SAVPF", "TLS", "DTLS", "SCTP", "AVPF", "udptl",
            ],
        );
        if i == -1 {
            return Err(Error::SdpInvalidValue(fields[2].to_owned()));
        }
        protos.push(proto.to_owned());
    }

    // <fmt>...
    let mut formats = vec![];
    for field in fields.iter().skip(3) {
        formats.push(field.to_string());
    }

    lexer.desc.media_descriptions.push(MediaDescription {
        media_name: MediaName {
            media: fields[0].to_owned(),
            port: RangedPort {
                value: port_value,
                range: port_range,
            },
            protos,
            formats,
        },
        media_title: None,
        connection_information: None,
        bandwidth: vec![],
        encryption_key: None,
        attributes: vec![],
    });

    Ok(Some(StateFn { f: s12 }))
}

fn unmarshal_media_title<'a, R: io::BufRead + io::Seek>(
    lexer: &mut Lexer<'a, R>,
) -> Result<Option<StateFn<'a, R>>> {
    let (value, _) = read_value(lexer.reader)?;

    if let Some(latest_media_desc) = lexer.desc.media_descriptions.last_mut() {
        latest_media_desc.media_title = Some(value);
        Ok(Some(StateFn { f: s16 }))
    } else {
        Err(Error::SdpEmptyTimeDescription)
    }
}

fn unmarshal_media_connection_information<'a, R: io::BufRead + io::Seek>(
    lexer: &mut Lexer<'a, R>,
) -> Result<Option<StateFn<'a, R>>> {
    let (value, _) = read_value(lexer.reader)?;

    if let Some(latest_media_desc) = lexer.desc.media_descriptions.last_mut() {
        latest_media_desc.connection_information = unmarshal_connection_information(&value)?;
        Ok(Some(StateFn { f: s15 }))
    } else {
        Err(Error::SdpEmptyTimeDescription)
    }
}

fn unmarshal_media_bandwidth<'a, R: io::BufRead + io::Seek>(
    lexer: &mut Lexer<'a, R>,
) -> Result<Option<StateFn<'a, R>>> {
    let (value, _) = read_value(lexer.reader)?;

    if let Some(latest_media_desc) = lexer.desc.media_descriptions.last_mut() {
        let bandwidth = unmarshal_bandwidth(&value)?;
        latest_media_desc.bandwidth.push(bandwidth);
        Ok(Some(StateFn { f: s15 }))
    } else {
        Err(Error::SdpEmptyTimeDescription)
    }
}

fn unmarshal_media_encryption_key<'a, R: io::BufRead + io::Seek>(
    lexer: &mut Lexer<'a, R>,
) -> Result<Option<StateFn<'a, R>>> {
    let (value, _) = read_value(lexer.reader)?;

    if let Some(latest_media_desc) = lexer.desc.media_descriptions.last_mut() {
        latest_media_desc.encryption_key = Some(value);
        Ok(Some(StateFn { f: s14 }))
    } else {
        Err(Error::SdpEmptyTimeDescription)
    }
}

fn unmarshal_media_attribute<'a, R: io::BufRead + io::Seek>(
    lexer: &mut Lexer<'a, R>,
) -> Result<Option<StateFn<'a, R>>> {
    let (value, _) = read_value(lexer.reader)?;

    let fields: Vec<&str> = value.splitn(2, ':').collect();
    let attribute = if fields.len() == 2 {
        Attribute {
            key: fields[0].to_owned(),
            value: Some(fields[1].to_owned()),
        }
    } else {
        Attribute {
            key: fields[0].to_owned(),
            value: None,
        }
    };

    if let Some(latest_media_desc) = lexer.desc.media_descriptions.last_mut() {
        latest_media_desc.attributes.push(attribute);
        Ok(Some(StateFn { f: s14 }))
    } else {
        Err(Error::SdpEmptyTimeDescription)
    }
}

fn parse_time_units(value: &str) -> Result<i64> {
    // Some time offsets in the protocol can be provided with a shorthand
    // notation. This code ensures to convert it to NTP timestamp format.
    let val = value.as_bytes();
    let len = val.len();
    let (num, factor) = match val.last() {
        Some(b'd') => (&value[..len - 1], 86400), // days
        Some(b'h') => (&value[..len - 1], 3600),  // hours
        Some(b'm') => (&value[..len - 1], 60),    // minutes
        Some(b's') => (&value[..len - 1], 1),     // seconds (allowed for completeness)
        _ => (value, 1),
    };
    num.parse::<i64>()?
        .checked_mul(factor)
        .ok_or_else(|| Error::SdpInvalidValue(value.to_owned()))
}