Skip to main content

rtci_sdp/description/
session.rs

1//! The session description — a whole SDP document.
2//!
3//! A [`SessionDescription`](crate::description::session::SessionDescription) is the session-level fields (`v=`, `o=`, `s=`, `t=`, …) followed by
4//! any number of [`MediaDescription`](crate::description::media::MediaDescription)s. `unmarshal` parses one
5//! from a string and `marshal` prints it back; the round trip is faithful, including attributes
6//! this crate does not interpret.
7//!
8//! The `ATTR_KEY_*` constants name the `a=` attributes WebRTC relies on — `mid`, `msid`,
9//! `setup`, `rtcp-mux`, `extmap` and the direction flags — and the `SEMANTIC_TOKEN_*` constants
10//! name the grouping semantics used with `a=group` and `a=msid-semantic`.
11
12use std::collections::HashMap;
13use std::convert::TryFrom;
14use std::io::Read;
15use std::str::FromStr;
16use std::time::{Duration, SystemTime, UNIX_EPOCH};
17use std::{fmt, io};
18
19use url::Url;
20
21use crate::grammar::{self, invalid, syntax};
22use crate::lexer::*;
23use crate::util::*;
24use shared::error::{Error, Result};
25
26use super::common::*;
27use super::media::*;
28
29/// Constants for SDP attributes used in JSEP
30pub const ATTR_KEY_CANDIDATE: &str = "candidate";
31/// `a=end-of-candidates`: ICE gathering for this section is complete.
32pub const ATTR_KEY_END_OF_CANDIDATES: &str = "end-of-candidates";
33/// `a=identity`: an identity assertion for the session.
34pub const ATTR_KEY_IDENTITY: &str = "identity";
35/// `a=group`: groups m-lines, as BUNDLE does.
36pub const ATTR_KEY_GROUP: &str = "group";
37/// `a=ssrc`: declares an SSRC and its attributes.
38pub const ATTR_KEY_SSRC: &str = "ssrc";
39/// `a=ssrc-group`: relates SSRCs, such as an RTX stream to its primary.
40pub const ATTR_KEY_SSRC_GROUP: &str = "ssrc-group";
41/// `a=msid`: associates a track with a media stream.
42pub const ATTR_KEY_MSID: &str = "msid";
43/// `a=msid-semantic`: declares the semantics used by `a=msid`.
44pub const ATTR_KEY_MSID_SEMANTIC: &str = "msid-semantic";
45/// `a=setup`: the DTLS role — `active`, `passive` or `actpass`.
46pub const ATTR_KEY_CONNECTION_SETUP: &str = "setup";
47/// `a=mid`: the media identification tag that names this m-line.
48pub const ATTR_KEY_MID: &str = "mid";
49/// `a=ice-lite`: the endpoint is an ICE-lite implementation.
50pub const ATTR_KEY_ICELITE: &str = "ice-lite";
51/// `a=rtcp-mux`: RTP and RTCP share one port.
52pub const ATTR_KEY_RTCPMUX: &str = "rtcp-mux";
53/// `a=rtcp-rsize`: reduced-size RTCP is supported.
54pub const ATTR_KEY_RTCPRSIZE: &str = "rtcp-rsize";
55/// `a=inactive`: neither send nor receive.
56pub const ATTR_KEY_INACTIVE: &str = "inactive";
57/// `a=recvonly`: receive only.
58pub const ATTR_KEY_RECV_ONLY: &str = "recvonly";
59/// `a=sendonly`: send only.
60pub const ATTR_KEY_SEND_ONLY: &str = "sendonly";
61/// `a=sendrecv`: send and receive.
62pub const ATTR_KEY_SEND_RECV: &str = "sendrecv";
63/// `a=extmap`: maps an RTP header-extension URI to an id.
64pub const ATTR_KEY_EXT_MAP: &str = "extmap";
65/// `a=extmap-allow-mixed`: one- and two-byte header extensions may be mixed.
66pub const ATTR_KEY_EXTMAP_ALLOW_MIXED: &str = "extmap-allow-mixed";
67/// `a=max-message-size`: the largest SCTP message this endpoint accepts.
68pub const ATTR_KEY_MAX_MESSAGE_SIZE: &str = "max-message-size";
69/// `a=rtcp-mux-only`: RTP and RTCP share one port and nothing else is supported (RFC 8858).
70pub const ATTR_KEY_RTCPMUX_ONLY: &str = "rtcp-mux-only";
71/// `a=rtcp`: the RTCP port and address (RFC 3605).
72pub const ATTR_KEY_RTCP: &str = "rtcp";
73/// `a=rtcp-fb`: an RTCP feedback capability (RFC 4585).
74pub const ATTR_KEY_RTCP_FB: &str = "rtcp-fb";
75/// `a=rtcp-xr`: RTCP extended reports (RFC 3611).
76pub const ATTR_KEY_RTCP_XR: &str = "rtcp-xr";
77/// `a=rtpmap`: the codec of a payload type.
78pub const ATTR_KEY_RTPMAP: &str = "rtpmap";
79/// `a=fmtp`: format-specific parameters.
80pub const ATTR_KEY_FMTP: &str = "fmtp";
81/// `a=ptime`: the preferred packet duration, in milliseconds.
82pub const ATTR_KEY_PTIME: &str = "ptime";
83/// `a=maxptime`: the longest packet duration, in milliseconds.
84pub const ATTR_KEY_MAXPTIME: &str = "maxptime";
85/// `a=framerate`: the maximum video frame rate.
86pub const ATTR_KEY_FRAMERATE: &str = "framerate";
87/// `a=imageattr`: image sizes a payload type sends or receives (RFC 6236).
88pub const ATTR_KEY_IMAGEATTR: &str = "imageattr";
89/// `a=content`: what a media stream shows (RFC 4796).
90pub const ATTR_KEY_CONTENT: &str = "content";
91/// `a=rid`: an RTP stream identifier and its restrictions (RFC 8851).
92pub const ATTR_KEY_RID: &str = "rid";
93/// `a=simulcast`: the simulcast streams of a media section (RFC 8853).
94pub const ATTR_KEY_SIMULCAST: &str = "simulcast";
95/// `a=ice-ufrag`: the ICE user name fragment.
96pub const ATTR_KEY_ICE_UFRAG: &str = "ice-ufrag";
97/// `a=ice-pwd`: the ICE password.
98pub const ATTR_KEY_ICE_PWD: &str = "ice-pwd";
99/// `a=ice-options`: the ICE options the agent supports.
100pub const ATTR_KEY_ICE_OPTIONS: &str = "ice-options";
101/// `a=ice-pacing`: the ICE pacing interval, in milliseconds.
102pub const ATTR_KEY_ICE_PACING: &str = "ice-pacing";
103/// `a=remote-candidates`: the remote candidates the controlling agent selected.
104pub const ATTR_KEY_REMOTE_CANDIDATES: &str = "remote-candidates";
105/// `a=fingerprint`: a certificate fingerprint (RFC 8122).
106pub const ATTR_KEY_FINGERPRINT: &str = "fingerprint";
107/// `a=tls-id`: the DTLS association identifier (RFC 8842).
108pub const ATTR_KEY_TLS_ID: &str = "tls-id";
109/// `a=sctp-port`: the SCTP port (RFC 8841).
110pub const ATTR_KEY_SCTP_PORT: &str = "sctp-port";
111/// `a=sctpmap`: the SCTP association of an old-style data section
112/// (draft-ietf-mmusic-sctp-sdp-05; replaced by `a=sctp-port`).
113pub const ATTR_KEY_SCTPMAP: &str = "sctpmap";
114/// `a=bundle-only`: the section is used only inside its BUNDLE group (RFC 9143).
115pub const ATTR_KEY_BUNDLE_ONLY: &str = "bundle-only";
116/// `a=cryptex`: RTP header extensions and CSRCs are encrypted (RFC 9335).
117pub const ATTR_KEY_CRYPTEX: &str = "cryptex";
118/// `BUNDLE`: the m= sections share one transport (RFC 9143).
119pub const SEMANTIC_TOKEN_BUNDLE: &str = "BUNDLE";
120
121/// Constants for semantic tokens used in JSEP
122pub const SEMANTIC_TOKEN_LIP_SYNCHRONIZATION: &str = "LS";
123/// `FID`: flow identification — the SSRCs carry the same content, as RTX does.
124pub const SEMANTIC_TOKEN_FLOW_IDENTIFICATION: &str = "FID";
125/// `FEC`: one SSRC carries error-correction data for another.
126pub const SEMANTIC_TOKEN_FORWARD_ERROR_CORRECTION: &str = "FEC";
127// https://datatracker.ietf.org/doc/html/rfc5956#section-4.1
128/// `FEC-FR`: the FEC framework grouping semantic.
129pub const SEMANTIC_TOKEN_FORWARD_ERROR_CORRECTION_FRAMEWORK: &str = "FEC-FR";
130/// `WMS`: WebRTC media streams, used with `a=msid-semantic`.
131pub const SEMANTIC_TOKEN_WEBRTC_MEDIA_STREAMS: &str = "WMS";
132
133/// The largest session description, in bytes, [`SessionDescription::unmarshal`] accepts. Real
134/// offers and answers are a few to a few hundred kilobytes.
135pub const MAX_SDP_SIZE: usize = 1 << 20;
136/// The most lines [`SessionDescription::unmarshal`] accepts in one session description.
137pub const MAX_SDP_LINES: usize = 65_536;
138/// The most `m=` sections [`SessionDescription::unmarshal`] accepts in one session description.
139pub const MAX_MEDIA_DESCRIPTIONS: usize = 1024;
140/// The most `a=` lines [`SessionDescription::unmarshal`] accepts at the session level, and in
141/// each `m=` section.
142pub const MAX_ATTRIBUTES_PER_SECTION: usize = 4096;
143/// The most formats [`SessionDescription::unmarshal`] accepts on one `m=` line. RTP payload
144/// types are 7 bits, so 128 distinct values exist.
145pub const MAX_FORMATS_PER_MEDIA: usize = 256;
146
147fn over_limit(what: &str, limit: usize) -> Error {
148    Error::SdpInvalidValue(format!("session description has more than {limit} {what}"))
149}
150
151/// Version describes the value provided by the "v=" field which gives
152/// the version of the Session Description Protocol.
153pub type Version = isize;
154
155/// A decimal number of any length, `1*DIGIT`: the `<sess-id>` and `<sess-version>` of an
156/// `o=` line (RFC 8866 section 9). The grammar sets no upper bound, so a compliant
157/// description may carry values beyond 64 bits (RFC 9429 section 5.2.1 has a JSEP endpoint
158/// generate them within 64 bits, and section 5.8 has it accept compliant SDP that does not
159/// follow its generation rules).
160///
161/// It keeps the digits as written, leading zeros included, so a description is written back
162/// as it was read; equality and order are those of the numbers.
163#[derive(Debug, Clone)]
164pub struct SdpDecimal(String);
165
166impl SdpDecimal {
167    /// `value` when it is `1*DIGIT`.
168    pub fn parse(value: &str) -> Option<Self> {
169        (!value.is_empty() && value.bytes().all(|b| b.is_ascii_digit()))
170            .then(|| SdpDecimal(value.to_owned()))
171    }
172
173    /// The digits as written.
174    pub fn as_str(&self) -> &str {
175        &self.0
176    }
177
178    /// The number, when it fits 64 bits.
179    pub fn to_u64(&self) -> Option<u64> {
180        self.0.parse().ok()
181    }
182
183    /// The digits without leading zeros ("0" for zero).
184    fn significant(&self) -> &str {
185        let trimmed = self.0.trim_start_matches('0');
186        if trimmed.is_empty() { "0" } else { trimmed }
187    }
188
189    /// The number plus one (RFC 3264 section 8: the version "MUST increment by one"), with
190    /// no upper bound.
191    pub fn incremented(&self) -> Self {
192        let mut digits: Vec<u8> = self.significant().bytes().collect();
193        let mut i = digits.len();
194        loop {
195            if i == 0 {
196                digits.insert(0, b'1');
197                break;
198            }
199            i -= 1;
200            if digits[i] == b'9' {
201                digits[i] = b'0';
202            } else {
203                digits[i] += 1;
204                break;
205            }
206        }
207        SdpDecimal(String::from_utf8(digits).unwrap_or_default())
208    }
209}
210
211impl Default for SdpDecimal {
212    fn default() -> Self {
213        SdpDecimal("0".to_owned())
214    }
215}
216
217impl From<u64> for SdpDecimal {
218    fn from(value: u64) -> Self {
219        SdpDecimal(value.to_string())
220    }
221}
222
223impl FromStr for SdpDecimal {
224    type Err = Error;
225
226    fn from_str(value: &str) -> Result<Self> {
227        SdpDecimal::parse(value).ok_or_else(|| syntax("1*DIGIT", value))
228    }
229}
230
231impl fmt::Display for SdpDecimal {
232    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
233        f.write_str(&self.0)
234    }
235}
236
237impl PartialEq for SdpDecimal {
238    fn eq(&self, other: &Self) -> bool {
239        self.significant() == other.significant()
240    }
241}
242
243impl Eq for SdpDecimal {}
244
245impl std::hash::Hash for SdpDecimal {
246    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
247        self.significant().hash(state);
248    }
249}
250
251impl PartialOrd for SdpDecimal {
252    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
253        Some(self.cmp(other))
254    }
255}
256
257impl Ord for SdpDecimal {
258    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
259        let (a, b) = (self.significant(), other.significant());
260        a.len().cmp(&b.len()).then_with(|| a.cmp(b))
261    }
262}
263
264impl PartialEq<u64> for SdpDecimal {
265    fn eq(&self, other: &u64) -> bool {
266        self.to_u64() == Some(*other)
267    }
268}
269
270/// Origin defines the structure for the "o=" field which provides the
271/// originator of the session plus a session identifier and version number.
272#[derive(Debug, Default, Clone)]
273pub struct Origin {
274    /// The originator's user name, or `-` when withheld.
275    pub username: String,
276    /// A globally unique session identifier, `1*DIGIT` of any length.
277    pub session_id: SdpDecimal,
278    /// Incremented on each modification of the session description; `1*DIGIT` of any
279    /// length.
280    pub session_version: SdpDecimal,
281    /// The network type, always `IN` in practice.
282    pub network_type: String,
283    /// The address type, `IP4` or `IP6`.
284    pub address_type: String,
285    /// The originator's address. WebRTC does not use it and sends a placeholder.
286    pub unicast_address: String,
287}
288
289impl fmt::Display for Origin {
290    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
291        write!(
292            f,
293            "{} {} {} {} {} {}",
294            self.username,
295            self.session_id,
296            self.session_version,
297            self.network_type,
298            self.address_type,
299            self.unicast_address,
300        )
301    }
302}
303
304impl Origin {
305    /// An empty session description with SDP version 0.
306    pub fn new() -> Self {
307        Origin {
308            username: "".to_owned(),
309            session_id: SdpDecimal::default(),
310            session_version: SdpDecimal::default(),
311            network_type: "".to_owned(),
312            address_type: "".to_owned(),
313            unicast_address: "".to_owned(),
314        }
315    }
316}
317
318/// SessionName describes a structured representations for the "s=" field
319/// and is the textual session name.
320pub type SessionName = String;
321
322/// EmailAddress describes a structured representations for the "e=" line
323/// which specifies email contact information for the person responsible for
324/// the conference.
325pub type EmailAddress = String;
326
327/// PhoneNumber describes a structured representations for the "p=" line
328/// specify phone contact information for the person responsible for the
329/// conference.
330pub type PhoneNumber = String;
331
332/// TimeZone is one `<adjustment time> <offset>` pair of a "z=" line, which describes
333/// repeated sessions scheduling.
334#[derive(Debug, Default, Clone, PartialEq, Eq)]
335pub struct TimeZone {
336    /// The time at which the offset takes effect.
337    pub adjustment_time: u64,
338    /// The offset from the session's base time, in seconds.
339    pub offset: i64,
340}
341
342impl fmt::Display for TimeZone {
343    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
344        write!(f, "{} {}", self.adjustment_time, self.offset)
345    }
346}
347
348/// TimeDescription describes the "t=", "r=" and "z=" fields of the session description,
349/// which specify the start and stop times of a session, its repeat intervals and durations,
350/// and the time zone adjustments of those repetitions.
351///
352/// RFC 8866 section 9: `time-description = time-field [repeat-description]`,
353/// `repeat-description = 1*repeat-field [zone-field]`.
354#[derive(Debug, Default, Clone)]
355pub struct TimeDescription {
356    /// `t=<start-time> <stop-time>`
357    ///
358    /// <https://www.rfc-editor.org/rfc/rfc8866#section-5.9>
359    pub timing: Timing,
360
361    /// `r=<repeat interval> <active duration> <offsets from start-time>`
362    ///
363    /// <https://www.rfc-editor.org/rfc/rfc8866#section-5.10>
364    pub repeat_times: Vec<RepeatTime>,
365
366    /// `z=<adjustment time> <offset> <adjustment time> <offset> ...`
367    ///
368    /// The zone adjustments of this time description's repetitions. Written after the `r=`
369    /// lines.
370    ///
371    /// <https://www.rfc-editor.org/rfc/rfc8866#section-5.11>
372    pub time_zones: Vec<TimeZone>,
373}
374
375/// Timing defines the "t=" field's structured representation for the start and
376/// stop times.
377#[derive(Debug, Default, Clone, PartialEq, Eq)]
378pub struct Timing {
379    /// Session start time in NTP seconds; `0` means unbounded.
380    pub start_time: u64,
381    /// Session stop time in NTP seconds; `0` means unbounded.
382    pub stop_time: u64,
383}
384
385impl fmt::Display for Timing {
386    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
387        write!(f, "{} {}", self.start_time, self.stop_time)
388    }
389}
390
391/// RepeatTime describes the "r=" fields of the session description which
392/// represents the intervals and durations for repeated scheduled sessions.
393#[derive(Debug, Default, Clone, PartialEq, Eq)]
394pub struct RepeatTime {
395    /// How often the session repeats, in seconds.
396    pub interval: i64,
397    /// How long each repetition lasts, in seconds.
398    pub duration: i64,
399    /// Offsets from the start time at which the session repeats.
400    pub offsets: Vec<i64>,
401}
402
403impl fmt::Display for RepeatTime {
404    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
405        write!(f, "{} {}", self.interval, self.duration)?;
406
407        for value in &self.offsets {
408            write!(f, " {value}")?;
409        }
410        Ok(())
411    }
412}
413
414/// SessionDescription is a a well-defined format for conveying sufficient
415/// information to discover and participate in a multimedia session.
416#[derive(Debug, Default, Clone)]
417pub struct SessionDescription {
418    /// `v=0`
419    ///
420    /// <https://www.rfc-editor.org/rfc/rfc8866#section-5.1>
421    pub version: Version,
422
423    /// `o=<username> <sess-id> <sess-version> <nettype> <addrtype> <unicast-address>`
424    ///
425    /// <https://www.rfc-editor.org/rfc/rfc8866#section-5.2>
426    pub origin: Origin,
427
428    /// `s=<session name>`
429    ///
430    /// Never empty in SDP: an empty name is written as `-`.
431    ///
432    /// <https://www.rfc-editor.org/rfc/rfc8866#section-5.3>
433    pub session_name: SessionName,
434
435    /// `i=<session description>`
436    ///
437    /// <https://www.rfc-editor.org/rfc/rfc8866#section-5.4>
438    pub session_information: Option<Information>,
439
440    /// `u=<uri>`: an RFC 3986 `URI-reference`, absolute or relative (RFC 8866 section 9:
441    /// `uri-field = %x75 "=" uri CRLF`, `uri = URI-reference`).
442    ///
443    /// <https://www.rfc-editor.org/rfc/rfc8866#section-5.5>
444    pub uri: Option<String>,
445
446    /// `e=<email-address>`, any number of lines.
447    ///
448    /// <https://www.rfc-editor.org/rfc/rfc8866#section-5.6>
449    pub email_addresses: Vec<EmailAddress>,
450
451    /// `p=<phone-number>`, any number of lines.
452    ///
453    /// <https://www.rfc-editor.org/rfc/rfc8866#section-5.6>
454    pub phone_numbers: Vec<PhoneNumber>,
455
456    /// `c=<nettype> <addrtype> <connection-address>`
457    ///
458    /// <https://www.rfc-editor.org/rfc/rfc8866#section-5.7>
459    pub connection_information: Option<ConnectionInformation>,
460
461    /// `b=<bwtype>:<bandwidth>`
462    ///
463    /// <https://www.rfc-editor.org/rfc/rfc8866#section-5.8>
464    pub bandwidth: Vec<Bandwidth>,
465
466    /// The time descriptions: `t=`, each with its `r=` and `z=` lines. SDP needs at least
467    /// one: an empty list is written as `t=0 0`.
468    ///
469    /// <https://www.rfc-editor.org/rfc/rfc8866#section-5.9>
470    pub time_descriptions: Vec<TimeDescription>,
471
472    /// Obsolete. RFC 8866 section 5.12: a `k=` line "MUST NOT be included in an SDP
473    /// description and MUST be discarded if received". The parser never sets this field
474    /// and nothing writes it; it is kept so that code naming it still builds.
475    pub encryption_key: Option<EncryptionKey>,
476
477    /// `a=<attribute>`
478    ///
479    /// `a=<attribute>:<value>`
480    ///
481    /// <https://www.rfc-editor.org/rfc/rfc8866#section-5.13>
482    pub attributes: Vec<Attribute>,
483
484    /// <https://www.rfc-editor.org/rfc/rfc8866#section-5.14>
485    pub media_descriptions: Vec<MediaDescription>,
486}
487
488/// Writes the description in the order RFC 8866 section 9 requires, whatever order its
489/// parts were set in: `v o s i u e* p* c b* (t r* z)+ a*`, then for each media description
490/// `m i c b* a*`.
491impl fmt::Display for SessionDescription {
492    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
493        write_key_value(f, "v=", Some(&self.version))?;
494        write_key_value(f, "o=", Some(&self.origin))?;
495        if self.session_name.is_empty() {
496            // Section 5.3: "The 's=' line MUST NOT be empty"; `s=-` names a nameless session.
497            write_key_value(f, "s=", Some("-"))?;
498        } else {
499            write_key_value(f, "s=", Some(&self.session_name))?;
500        }
501
502        write_key_value(f, "i=", self.session_information.as_ref())?;
503
504        if let Some(uri) = &self.uri {
505            write_key_value(f, "u=", Some(uri))?;
506        }
507        for email_address in &self.email_addresses {
508            write_key_value(f, "e=", Some(email_address))?;
509        }
510        for phone_number in &self.phone_numbers {
511            write_key_value(f, "p=", Some(phone_number))?;
512        }
513        if let Some(connection_information) = &self.connection_information {
514            write_key_value(f, "c=", Some(&connection_information))?;
515        }
516
517        for bandwidth in &self.bandwidth {
518            write_key_value(f, "b=", Some(&bandwidth))?;
519        }
520        if self.time_descriptions.is_empty() {
521            // Section 9: `1*time-description`.
522            write_key_value(f, "t=", Some("0 0"))?;
523        }
524        for time_description in &self.time_descriptions {
525            write_key_value(f, "t=", Some(&time_description.timing))?;
526            for repeat_time in &time_description.repeat_times {
527                write_key_value(f, "r=", Some(&repeat_time))?;
528            }
529            write_key_slice_of_values(f, "z=", &time_description.time_zones)?;
530        }
531
532        for attribute in &self.attributes {
533            write_key_value(f, "a=", Some(&attribute))?;
534        }
535
536        for media_description in &self.media_descriptions {
537            write_key_value(f, "m=", Some(&media_description.media_name))?;
538            write_key_value(f, "i=", media_description.media_title.as_ref())?;
539            if let Some(connection_information) = &media_description.connection_information {
540                write_key_value(f, "c=", Some(&connection_information))?;
541            }
542            for bandwidth in &media_description.bandwidth {
543                write_key_value(f, "b=", Some(&bandwidth))?;
544            }
545            for attribute in &media_description.attributes {
546                write_key_value(f, "a=", Some(&attribute))?;
547            }
548        }
549
550        Ok(())
551    }
552}
553
554/// What [`SessionDescription::unmarshal_with_options`] accepts beyond the RFC 8866 grammar.
555///
556/// [`SessionDescription::unmarshal`] parses with [`ParseOptions::strict`]: RFC 9429 section
557/// 5.8 has a description that is not well formed rejected, so the engine's own parsing is
558/// the grammar and nothing else. An application that has to read what other software calls
559/// SDP can ask for each leniency by name, or for all of them with
560/// [`ParseOptions::lenient`].
561///
562/// # What is accepted in every mode
563///
564/// These are the places where the parser is deliberately wider than the grammar, each for
565/// a reason:
566///
567/// * A line may end in a bare LF instead of CRLF. RFC 8866 section 5: "parsers SHOULD be
568///   tolerant and also accept lines terminated with a single newline character".
569/// * The last line may have no line ending, and empty lines may follow it. Descriptions
570///   that went through a text field or a `trim()` look like this.
571/// * `z=` may follow a `t=` line that has no `r=` line. RFC 4566 allowed it, and RFC 8866
572///   moved `z=` into the repeat description; a description written to RFC 4566 still parses.
573/// * `k=` lines are checked for syntax and dropped (RFC 8866 section 5.12: "MUST be
574///   discarded if received").
575/// * `a=name:` with an empty value is kept as an attribute whose value is the empty string.
576///   RFC 3611 defines one (`a=rtcp-xr:`), although the RFC 8866 `byte-string` is never empty.
577/// * An attribute this crate does not know is kept as it is, at either level (RFC 8866
578///   section 5.13: "an attribute that is not understood MUST be ignored"). The typed
579///   accessors are where the value of a known attribute is checked.
580/// * Several `c=` lines in one media description are accepted; the last one is kept.
581///
582/// # What is always refused
583///
584/// A type letter RFC 8866 does not define (section 5: such a description is ignored or
585/// rejected whole), a line that is not `<type>=<value>`, NUL, a bare CR, text that is not
586/// UTF-8 when the description names no other set with `a=charset` (`unmarshal`, from bytes),
587/// session-level lines out of order, and a
588/// description without `v=`, `o=`, `s=` or `t=`.
589#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
590pub struct ParseOptions {
591    /// Skip empty lines before and between lines, as some media players accept.
592    pub blank_lines: bool,
593    /// Accept `i=`, `c=`, `b=` and `k=` after `a=` lines inside a media description. Some
594    /// gateways write them so; RFC 8866 section 5 has them "in exactly the order given".
595    pub unordered_media_lines: bool,
596    /// Do not check what the fields of a line contain beyond what the parser needs:
597    /// fields may be separated and surrounded by any run of spaces and tabs; `t=` times may
598    /// be any number; addresses in `o=` and `c=` need only be free of white space (and `c=`
599    /// may lack one); `i=`, `e=` and `p=` text is kept unchecked; `s=` may be empty; extra
600    /// fields after the stop time of `t=` are ignored.
601    pub loose_fields: bool,
602}
603
604impl ParseOptions {
605    /// The RFC 8866 grammar, with only the tolerance every mode has. The default.
606    pub const fn strict() -> Self {
607        ParseOptions {
608            blank_lines: false,
609            unordered_media_lines: false,
610            loose_fields: false,
611        }
612    }
613
614    /// Every leniency.
615    pub const fn lenient() -> Self {
616        ParseOptions {
617            blank_lines: true,
618            unordered_media_lines: true,
619            loose_fields: true,
620        }
621    }
622}
623
624/// Reset cleans the SessionDescription, and sets all fields back to their default values
625impl SessionDescription {
626    /// A session description with the session-level lines RFC 9429 section 5.2.1 gives an
627    /// offer: `v=0`, `o=- <sess-id> <sess-version> IN IP4 0.0.0.0` with a random 63-bit
628    /// session id, `s=-` and `t=0 0`.
629    ///
630    /// `_identity` is ignored. It used to add a bare `a=identity`, which is not SDP: the
631    /// attribute carries an assertion (RFC 8827 section 5). An application that has one
632    /// adds it with `with_typed(&Identity)`.
633    pub fn new_jsep_session_description(_identity: bool) -> Self {
634        SessionDescription {
635            version: 0,
636            origin: Origin {
637                username: "-".to_string(),
638                session_id: new_session_id().into(),
639                session_version: u64::from(
640                    SystemTime::now() // Exemption: wall-clock is correct here to generate random SDP session version
641                        .duration_since(UNIX_EPOCH)
642                        .unwrap_or_else(|_| Duration::from_secs(0))
643                        .subsec_nanos(),
644                )
645                .into(),
646                network_type: "IN".to_string(),
647                address_type: "IP4".to_string(),
648                unicast_address: "0.0.0.0".to_string(),
649            },
650            session_name: "-".to_string(),
651            session_information: None,
652            uri: None,
653            email_addresses: vec![],
654            phone_numbers: vec![],
655            connection_information: None,
656            bandwidth: vec![],
657            time_descriptions: vec![TimeDescription {
658                timing: Timing {
659                    start_time: 0,
660                    stop_time: 0,
661                },
662                repeat_times: vec![],
663                time_zones: vec![],
664            }],
665            encryption_key: None,
666            attributes: vec![],
667            media_descriptions: vec![],
668        }
669    }
670
671    /// WithPropertyAttribute adds a property attribute 'a=key' to the session description
672    pub fn with_property_attribute(mut self, key: String) -> Self {
673        self.attributes.push(Attribute::new(key, None));
674        self
675    }
676
677    /// WithValueAttribute adds a value attribute 'a=key:value' to the session description
678    pub fn with_value_attribute(mut self, key: String, value: String) -> Self {
679        self.attributes.push(Attribute::new(key, Some(value)));
680        self
681    }
682
683    /// WithFingerprint adds a fingerprint to the session description
684    pub fn with_fingerprint(self, algorithm: String, value: String) -> Self {
685        self.with_value_attribute("fingerprint".to_string(), algorithm + " " + value.as_str())
686    }
687
688    /// WithMedia adds a media description to the session description
689    pub fn with_media(mut self, md: MediaDescription) -> Self {
690        self.media_descriptions.push(md);
691        self
692    }
693
694    fn build_codec_map(&self) -> HashMap<u8, Codec> {
695        let mut codecs: HashMap<u8, Codec> = HashMap::new();
696
697        for m in &self.media_descriptions {
698            codecs.extend(m.codecs());
699        }
700
701        codecs
702    }
703
704    /// get_codec_for_payload_type scans the SessionDescription for the given payload type and returns the codec
705    pub fn get_codec_for_payload_type(&self, payload_type: u8) -> Result<Codec> {
706        let codecs = self.build_codec_map();
707
708        if let Some(codec) = codecs.get(&payload_type) {
709            Ok(codec.clone())
710        } else {
711            Err(Error::PayloadTypeNotFound)
712        }
713    }
714
715    /// get_payload_type_for_codec scans the SessionDescription for a codec that matches the provided codec
716    /// as closely as possible and returns its payload type
717    pub fn get_payload_type_for_codec(&self, wanted: &Codec) -> Result<u8> {
718        let codecs = self.build_codec_map();
719
720        for (payload_type, codec) in codecs.iter() {
721            if codecs_match(wanted, codec) {
722                return Ok(*payload_type);
723            }
724        }
725
726        Err(Error::CodecNotFound)
727    }
728
729    /// Returns whether an attribute exists
730    pub fn has_attribute(&self, key: &str) -> bool {
731        self.attributes.iter().any(|a| a.key == key)
732    }
733
734    /// Attribute returns the value of an attribute and if it exists
735    pub fn attribute(&self, key: &str) -> Option<&String> {
736        for a in &self.attributes {
737            if a.key == key {
738                return a.value.as_ref();
739            }
740        }
741        None
742    }
743
744    /// The value of the first session-level `b=` line of `kind`, in the unit of that
745    /// modifier.
746    pub fn bandwidth_of(&self, kind: BandwidthKind) -> Option<u64> {
747        find_bandwidth(&self.bandwidth, kind)
748    }
749
750    crate::attribute::common_accessors!();
751    crate::attribute::session_accessors!();
752
753    /// Marshal takes a SDP struct to text, in the order RFC 8866 section 9 gives:
754    ///
755    /// ```text
756    /// Session description
757    ///    v=  (protocol version)
758    ///    o=  (originator and session identifier)
759    ///    s=  (session name)
760    ///    i=* (session information)
761    ///    u=* (URI of description)
762    ///    e=* (zero or more email address lines)
763    ///    p=* (zero or more phone number lines)
764    ///    c=* (connection information -- not required if included in all media)
765    ///    b=* (zero or more bandwidth information lines)
766    ///    One or more time descriptions:
767    ///       t=  (time the session is active)
768    ///       r=* (zero or more repeat times)
769    ///       z=* (time zone adjustments of those repeat times)
770    ///    a=* (zero or more session attribute lines)
771    ///    Zero or more media descriptions:
772    ///       m=  (media name and transport address)
773    ///       i=* (media title)
774    ///       c=* (connection information -- optional if included at session level)
775    ///       b=* (zero or more bandwidth information lines)
776    ///       a=* (zero or more media attribute lines)
777    /// ```
778    ///
779    /// `k=` is never written (section 5.12). An empty session name is written as `s=-` and
780    /// an empty list of time descriptions as `t=0 0`, so that what comes out has the
781    /// required lines. Field values are written as they are: build them from parsed or
782    /// checked input.
783    pub fn marshal(&self) -> String {
784        self.to_string()
785    }
786
787    /// Unmarshal deserializes a session description, with [`ParseOptions::strict`]: the
788    /// RFC 8866 section 9 grammar, line by line and in its order.
789    ///
790    /// See [`ParseOptions`] for what is accepted beyond the grammar, and for what is
791    /// refused. Attribute values are kept as text: use the typed accessors
792    /// (`mid()`, `rtpmaps()`, `candidates()`, ...) or [`SessionDescription::validate`] to
793    /// check them.
794    ///
795    /// The input is bounded: [`MAX_SDP_SIZE`] bytes, [`MAX_SDP_LINES`] lines,
796    /// [`MAX_MEDIA_DESCRIPTIONS`] media descriptions, [`MAX_ATTRIBUTES_PER_SECTION`]
797    /// attributes at each level and [`MAX_FORMATS_PER_MEDIA`] formats on an `m=` line.
798    pub fn unmarshal<R: io::BufRead + io::Seek>(reader: &mut R) -> Result<Self> {
799        Self::unmarshal_with_options(reader, &ParseOptions::strict())
800    }
801
802    /// [`SessionDescription::unmarshal`] with the leniencies `options` names.
803    pub fn unmarshal_with_options<R: io::BufRead + io::Seek>(
804        reader: &mut R,
805        options: &ParseOptions,
806    ) -> Result<Self> {
807        let start = reader.stream_position()?;
808        let end = reader.seek(io::SeekFrom::End(0))?;
809        reader.seek(io::SeekFrom::Start(start))?;
810        if end.saturating_sub(start) > MAX_SDP_SIZE as u64 {
811            return Err(over_limit("bytes", MAX_SDP_SIZE));
812        }
813
814        let mut bytes = Vec::with_capacity(end.saturating_sub(start) as usize);
815        io::Read::take(&mut *reader, MAX_SDP_SIZE as u64 + 1).read_to_end(&mut bytes)?;
816        if bytes.len() > MAX_SDP_SIZE {
817            return Err(over_limit("bytes", MAX_SDP_SIZE));
818        }
819        let text = decode(&bytes)?;
820        Self::parse_with_options(&text, options)
821    }
822
823    /// The character set the session name and information are in (RFC 8866 section 6.10,
824    /// `a=charset`): UTF-8 when the description names none.
825    pub fn charset(&self) -> Charset {
826        self.attribute(ATTR_KEY_CHARSET)
827            .map_or(Charset::Utf8, |name| Charset::named(name))
828    }
829
830    /// Parses a session description from text, with the leniencies `options` names.
831    pub fn parse_with_options(text: &str, options: &ParseOptions) -> Result<Self> {
832        Self::parse_located(text, options).map_err(|err| err.error)
833    }
834
835    /// [`Self::parse_with_options`], saying which line a syntax error is on (W3C webrtc-pc
836    /// section 11.1: an `sdp-syntax-error` carries its `sdpLineNumber`).
837    ///
838    /// # Errors
839    ///
840    /// The error [`Self::parse_with_options`] returns, with the number (from 1, blank lines
841    /// counted) of the line it is about; `None` for an error about the description as a whole
842    /// (its size, or a missing `t=` line at its end).
843    pub fn parse_located(
844        text: &str,
845        options: &ParseOptions,
846    ) -> std::result::Result<Self, SdpParseError> {
847        let unlocated = |error| SdpParseError {
848            line_number: None,
849            error,
850        };
851        if text.len() > MAX_SDP_SIZE {
852            return Err(unlocated(over_limit("bytes", MAX_SDP_SIZE)));
853        }
854        let mut parser = Parser::new(*options);
855        let lines = lines_located(text, options.blank_lines, MAX_SDP_LINES).map_err(
856            |(number, error)| SdpParseError {
857                line_number: Some(number),
858                error,
859            },
860        )?;
861        for line in lines {
862            let number = line.number;
863            parser.line(line).map_err(|error| SdpParseError {
864                line_number: Some(number),
865                error,
866            })?;
867        }
868        parser.finish().map_err(unlocated)
869    }
870}
871
872/// RFC 3986 section 4.1 `URI-reference`: a URI, or a relative reference (RFC 8866 section
873/// 9 has `uri = URI-reference`). An absolute one is what the `url` crate parses; a relative
874/// one has only the characters of the grammar (unreserved, sub-delims, `:` `@` `/` `?` `#`
875/// `[` `]`, and `%` with two hex digits) and no `:` in its first segment (`path-noscheme`).
876fn is_uri_reference(value: &str) -> bool {
877    if value.is_empty() {
878        return false;
879    }
880    let bytes = value.as_bytes();
881    let mut i = 0;
882    while i < bytes.len() {
883        let b = bytes[i];
884        let ok = b.is_ascii_alphanumeric() || b"-._~!$&'()*+,;=:@/?#[]".contains(&b);
885        if b == b'%' {
886            if !bytes.get(i + 1).is_some_and(u8::is_ascii_hexdigit)
887                || !bytes.get(i + 2).is_some_and(u8::is_ascii_hexdigit)
888            {
889                return false;
890            }
891            i += 3;
892            continue;
893        }
894        if !ok {
895            return false;
896        }
897        i += 1;
898    }
899    let first_segment = value.split(['/', '?', '#']).next().unwrap_or_default();
900    match first_segment.split_once(':') {
901        // A scheme: the reference is a URI.
902        Some((scheme, _)) => {
903            scheme
904                .bytes()
905                .next()
906                .is_some_and(|b| b.is_ascii_alphabetic())
907                && scheme
908                    .bytes()
909                    .all(|b| b.is_ascii_alphanumeric() || b"+-.".contains(&b))
910                && Url::parse(value).is_ok()
911        }
912        None => true,
913    }
914}
915
916/// The `a=charset` attribute (RFC 8866 section 6.10).
917pub const ATTR_KEY_CHARSET: &str = "charset";
918
919/// The character set of a description's charset-dependent fields (`s=`, `i=`), from its
920/// `a=charset` (RFC 8866 section 6.10).
921#[derive(Debug, Clone, PartialEq, Eq)]
922pub enum Charset {
923    /// ISO-10646 in UTF-8, the default.
924    Utf8,
925    /// ISO-8859-1.
926    Latin1,
927    /// US-ASCII.
928    Ascii,
929    /// A character set this crate does not support (or not a registered one): its strings
930    /// are octet strings (RFC 8866 section 6.10: "If the identifier is not recognized or not
931    /// supported, all strings that are affected by it SHOULD be regarded as octet strings"),
932    /// each octet read as the character of that code point.
933    Other(String),
934}
935
936impl Charset {
937    /// The character set `name` identifies. RFC 8866 section 6.10: the identifier "MUST be
938    /// compared against identifiers from the 'Name' or 'Preferred MIME Name' field of the
939    /// registry using a case-insensitive comparison"; the aliases of the IANA Character Sets
940    /// registry for the three sets are recognised too.
941    pub fn named(name: &str) -> Self {
942        const UTF8: [&str; 2] = ["UTF-8", "csUTF8"];
943        const LATIN1: [&str; 10] = [
944            "ISO-8859-1",
945            "ISO_8859-1:1987",
946            "ISO_8859-1",
947            "iso-ir-100",
948            "latin1",
949            "l1",
950            "IBM819",
951            "CP819",
952            "csISOLatin1",
953            "ISO-8859-1:1987",
954        ];
955        const ASCII: [&str; 11] = [
956            "US-ASCII",
957            "ANSI_X3.4-1968",
958            "iso-ir-6",
959            "ANSI_X3.4-1986",
960            "ISO_646.irv:1991",
961            "ISO646-US",
962            "us",
963            "IBM367",
964            "cp367",
965            "csASCII",
966            "ASCII",
967        ];
968        let name = name.trim();
969        let is = |names: &[&str]| names.iter().any(|n| n.eq_ignore_ascii_case(name));
970        if is(&UTF8) {
971            Charset::Utf8
972        } else if is(&LATIN1) {
973            Charset::Latin1
974        } else if is(&ASCII) {
975            Charset::Ascii
976        } else {
977            Charset::Other(name.to_owned())
978        }
979    }
980}
981
982/// The `a=charset` value of a description's session part, read from its bytes (the
983/// attribute is ASCII, whatever set it names).
984fn declared_charset(bytes: &[u8]) -> Option<Charset> {
985    for line in bytes.split(|&b| b == b'\n') {
986        let line = line.strip_suffix(b"\r").unwrap_or(line);
987        if line.starts_with(b"m=") {
988            return None;
989        }
990        if let Some(value) = line.strip_prefix(b"a=charset:") {
991            return core::str::from_utf8(value).ok().map(Charset::named);
992        }
993    }
994    None
995}
996
997/// The text of a description given as bytes. RFC 8866 section 5: "the 'a=charset' attribute
998/// ... is used to specify the character set"; without one, or with UTF-8, the text is UTF-8
999/// and other bytes refuse it. ISO-8859-1 is decoded as such, US-ASCII must be 7-bit, and an
1000/// unsupported set's text is kept as octets (each byte the character of its code point; RFC
1001/// 8866 section 6.10). Every other field is ASCII in all of these.
1002fn decode(bytes: &[u8]) -> Result<std::borrow::Cow<'_, str>> {
1003    match declared_charset(bytes) {
1004        None | Some(Charset::Utf8) => core::str::from_utf8(bytes)
1005            .map(std::borrow::Cow::Borrowed)
1006            .map_err(|_| Error::SdpInvalidSyntax("the description is not UTF-8".to_owned())),
1007        Some(Charset::Ascii) => {
1008            if bytes.is_ascii() {
1009                Ok(std::borrow::Cow::Owned(
1010                    bytes.iter().map(|&b| char::from(b)).collect(),
1011                ))
1012            } else {
1013                Err(Error::SdpInvalidSyntax(
1014                    "a=charset:US-ASCII and a byte above 127 (RFC 8866 section 6.10)".to_owned(),
1015                ))
1016            }
1017        }
1018        Some(Charset::Latin1 | Charset::Other(_)) => Ok(std::borrow::Cow::Owned(
1019            bytes.iter().map(|&b| char::from(b)).collect(),
1020        )),
1021    }
1022}
1023
1024/// A description that does not parse, and where: what
1025/// [`SessionDescription::parse_located`] returns.
1026#[derive(Debug, PartialEq)]
1027pub struct SdpParseError {
1028    /// The line the error is about, from 1 (blank lines counted); `None` when it is about the
1029    /// description as a whole.
1030    pub line_number: Option<usize>,
1031    /// What is wrong.
1032    pub error: Error,
1033}
1034
1035impl From<SessionDescription> for String {
1036    fn from(sdp: SessionDescription) -> String {
1037        sdp.marshal()
1038    }
1039}
1040
1041impl TryFrom<String> for SessionDescription {
1042    type Error = Error;
1043    fn try_from(sdp_string: String) -> Result<Self> {
1044        SessionDescription::parse_with_options(&sdp_string, &ParseOptions::strict())
1045    }
1046}
1047
1048impl FromStr for SessionDescription {
1049    type Err = Error;
1050    fn from_str(sdp: &str) -> Result<Self> {
1051        SessionDescription::parse_with_options(sdp, &ParseOptions::strict())
1052    }
1053}
1054
1055/// Where the parser is in `v o s i u e* p* c b* (t r* z)+ k a* m*`: the rank of the
1056/// earliest line type that may still come.
1057#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
1058enum SessionRank {
1059    Version,
1060    Origin,
1061    Name,
1062    Information,
1063    Uri,
1064    Email,
1065    Phone,
1066    Connection,
1067    Bandwidth,
1068    Time,
1069    Key,
1070    Attribute,
1071}
1072
1073/// Where the parser is inside a time description.
1074#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1075enum TimeState {
1076    /// No `t=` line yet, or a line that is not part of a time description came since.
1077    Outside,
1078    /// The last line was `t=`.
1079    Timing,
1080    /// The last line was `r=`.
1081    Repeat,
1082    /// The last line was `z=`.
1083    Zone,
1084}
1085
1086/// Where the parser is in `m i c* b* k a*`.
1087#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
1088enum MediaRank {
1089    Information,
1090    Connection,
1091    Bandwidth,
1092    Key,
1093    Attribute,
1094}
1095
1096struct Parser {
1097    options: ParseOptions,
1098    desc: SessionDescription,
1099    rank: SessionRank,
1100    time: TimeState,
1101    /// `Some` once the first `m=` line was read.
1102    media: Option<MediaState>,
1103}
1104
1105struct MediaState {
1106    rank: MediaRank,
1107    has_title: bool,
1108    has_key: bool,
1109}
1110
1111fn out_of_order(kind: u8) -> Error {
1112    Error::SdpInvalidSyntax(format!(
1113        "a `{}=` line where the grammar has none",
1114        kind as char
1115    ))
1116}
1117
1118impl Parser {
1119    fn new(options: ParseOptions) -> Self {
1120        Parser {
1121            options,
1122            desc: SessionDescription::default(),
1123            rank: SessionRank::Version,
1124            time: TimeState::Outside,
1125            media: None,
1126        }
1127    }
1128
1129    fn finish(self) -> Result<SessionDescription> {
1130        // v=, o=, s= and one t= are required, in that order: a t= line means all four.
1131        if self.desc.time_descriptions.is_empty() {
1132            return Err(Error::SdpInvalidSyntax(
1133                "the description ends before its `t=` line".to_owned(),
1134            ));
1135        }
1136        Ok(self.desc)
1137    }
1138
1139    /// The fields of a structured line: separated by one space, or by any white space when
1140    /// `loose_fields` is set.
1141    fn fields<'a>(&self, what: &str, value: &'a str) -> Result<Vec<&'a str>> {
1142        if self.options.loose_fields {
1143            let fields: Vec<&str> = value.split_whitespace().collect();
1144            if fields.is_empty() {
1145                return Err(syntax(what, value));
1146            }
1147            Ok(fields)
1148        } else {
1149            grammar::fields(what, value)
1150        }
1151    }
1152
1153    fn line(&mut self, line: Line<'_>) -> Result<()> {
1154        if !matches!(
1155            line.kind,
1156            b'v' | b'o'
1157                | b's'
1158                | b'i'
1159                | b'u'
1160                | b'e'
1161                | b'p'
1162                | b'c'
1163                | b'b'
1164                | b't'
1165                | b'r'
1166                | b'z'
1167                | b'k'
1168                | b'a'
1169                | b'm'
1170        ) {
1171            // RFC 8866 section 5: a parser "MUST completely ignore or reject any session
1172            // description that contains a type letter that it does not understand".
1173            return Err(Error::SdpInvalidSyntax(format!(
1174                "unknown line type `{}=`",
1175                line.kind.escape_ascii()
1176            )));
1177        }
1178
1179        if line.kind == b'm' {
1180            // A media description may only start once the session level is complete.
1181            if self.desc.time_descriptions.is_empty() {
1182                return Err(out_of_order(line.kind));
1183            }
1184            self.media_line(line.value)?;
1185            self.media = Some(MediaState {
1186                rank: MediaRank::Information,
1187                has_title: false,
1188                has_key: false,
1189            });
1190            return Ok(());
1191        }
1192
1193        if self.media.is_some() {
1194            self.media_level(line)
1195        } else {
1196            self.session_level(line)
1197        }
1198    }
1199
1200    fn session_level(&mut self, line: Line<'_>) -> Result<()> {
1201        use SessionRank as R;
1202
1203        let value = line.value;
1204        let was_time = self.time;
1205        if !matches!(line.kind, b'r' | b'z') {
1206            self.time = TimeState::Outside;
1207        }
1208
1209        // (rank of this line, rank of the earliest line that may follow it)
1210        let (rank, next) = match line.kind {
1211            b'v' => (R::Version, R::Origin),
1212            b'o' => (R::Origin, R::Name),
1213            b's' => (R::Name, R::Information),
1214            b'i' => (R::Information, R::Uri),
1215            b'u' => (R::Uri, R::Email),
1216            b'e' => (R::Email, R::Email),
1217            b'p' => (R::Phone, R::Phone),
1218            b'c' => (R::Connection, R::Bandwidth),
1219            b'b' => (R::Bandwidth, R::Bandwidth),
1220            b't' | b'r' | b'z' => (R::Time, R::Time),
1221            b'k' => (R::Key, R::Attribute),
1222            b'a' => (R::Attribute, R::Attribute),
1223            _ => return Err(out_of_order(line.kind)),
1224        };
1225
1226        // v=, o= and s= are required and come first, in that order; a t= line is required
1227        // before anything that follows the time descriptions.
1228        let allowed = match self.rank {
1229            R::Version | R::Origin | R::Name => rank == self.rank,
1230            earliest => {
1231                rank >= earliest && (rank <= R::Time || !self.desc.time_descriptions.is_empty())
1232            }
1233        };
1234        if !allowed {
1235            return Err(out_of_order(line.kind));
1236        }
1237
1238        match line.kind {
1239            b'v' => {
1240                // `1*DIGIT`, and RFC 9429 section 5.8.1: the version is 0.
1241                if grammar::digits::<u32>("v=", value)? != 0 {
1242                    return Err(syntax("v=", value));
1243                }
1244                self.desc.version = 0;
1245            }
1246            b'o' => self.desc.origin = self.origin(value)?,
1247            b's' => {
1248                if !(grammar::is_byte_string(value)
1249                    || (value.is_empty() && self.options.loose_fields))
1250                {
1251                    return Err(syntax("s=", value));
1252                }
1253                self.desc.session_name = value.to_owned();
1254            }
1255            b'i' => self.desc.session_information = Some(self.text("i=", value)?),
1256            b'u' => {
1257                if !is_uri_reference(value) {
1258                    return Err(syntax("u=", value));
1259                }
1260                self.desc.uri = Some(value.to_owned());
1261            }
1262            b'e' => {
1263                if !self.options.loose_fields && !is_email_address(value) {
1264                    return Err(syntax("e=", value));
1265                }
1266                self.desc.email_addresses.push(value.to_owned());
1267            }
1268            b'p' => {
1269                if !self.options.loose_fields && !is_phone_number(value) {
1270                    return Err(syntax("p=", value));
1271                }
1272                self.desc.phone_numbers.push(value.to_owned());
1273            }
1274            b'c' => self.desc.connection_information = Some(self.connection(value)?),
1275            b'b' => self.desc.bandwidth.push(self.bandwidth(value)?),
1276            b't' => {
1277                let timing = self.timing(value)?;
1278                self.desc.time_descriptions.push(TimeDescription {
1279                    timing,
1280                    repeat_times: vec![],
1281                    time_zones: vec![],
1282                });
1283                self.time = TimeState::Timing;
1284            }
1285            b'r' => {
1286                if !matches!(was_time, TimeState::Timing | TimeState::Repeat) {
1287                    return Err(out_of_order(line.kind));
1288                }
1289                let repeat = self.repeat(value)?;
1290                // `was_time` is not `Outside`, so a time description exists.
1291                if let Some(last) = self.desc.time_descriptions.last_mut() {
1292                    last.repeat_times.push(repeat);
1293                }
1294                self.time = TimeState::Repeat;
1295            }
1296            b'z' => {
1297                if !matches!(was_time, TimeState::Timing | TimeState::Repeat) {
1298                    return Err(out_of_order(line.kind));
1299                }
1300                let zones = self.zones(value)?;
1301                if let Some(last) = self.desc.time_descriptions.last_mut() {
1302                    last.time_zones = zones;
1303                }
1304                self.time = TimeState::Zone;
1305            }
1306            b'k' => check_key(value)?,
1307            _ => {
1308                if self.desc.attributes.len() >= MAX_ATTRIBUTES_PER_SECTION {
1309                    return Err(over_limit("session attributes", MAX_ATTRIBUTES_PER_SECTION));
1310                }
1311                self.desc.attributes.push(parse_attribute(value)?);
1312            }
1313        }
1314
1315        self.rank = next;
1316        Ok(())
1317    }
1318
1319    fn media_level(&mut self, line: Line<'_>) -> Result<()> {
1320        use MediaRank as M;
1321
1322        let value = line.value;
1323        let (rank, next) = match line.kind {
1324            b'i' => (M::Information, M::Connection),
1325            b'c' => (M::Connection, M::Connection),
1326            b'b' => (M::Bandwidth, M::Bandwidth),
1327            b'k' => (M::Key, M::Attribute),
1328            b'a' => (M::Attribute, M::Attribute),
1329            _ => return Err(out_of_order(line.kind)),
1330        };
1331
1332        let unordered = self.options.unordered_media_lines;
1333        let Some(state) = self.media.as_mut() else {
1334            return Err(out_of_order(line.kind));
1335        };
1336        if !unordered && rank < state.rank {
1337            return Err(out_of_order(line.kind));
1338        }
1339        // One i= and one k= at most, in any mode.
1340        match line.kind {
1341            b'i' if std::mem::replace(&mut state.has_title, true) => {
1342                return Err(out_of_order(line.kind));
1343            }
1344            b'k' if std::mem::replace(&mut state.has_key, true) => {
1345                return Err(out_of_order(line.kind));
1346            }
1347            _ => {}
1348        }
1349        state.rank = state.rank.max(next);
1350
1351        match line.kind {
1352            b'i' => {
1353                let title = self.text("i=", value)?;
1354                self.last_media()?.media_title = Some(title);
1355            }
1356            b'c' => {
1357                let connection = self.connection(value)?;
1358                self.last_media()?.connection_information = Some(connection);
1359            }
1360            b'b' => {
1361                let bandwidth = self.bandwidth(value)?;
1362                self.last_media()?.bandwidth.push(bandwidth);
1363            }
1364            b'k' => check_key(value)?,
1365            _ => {
1366                let attribute = parse_attribute(value)?;
1367                let media = self.last_media()?;
1368                if media.attributes.len() >= MAX_ATTRIBUTES_PER_SECTION {
1369                    return Err(over_limit(
1370                        "attributes in one media section",
1371                        MAX_ATTRIBUTES_PER_SECTION,
1372                    ));
1373                }
1374                media.attributes.push(attribute);
1375            }
1376        }
1377        Ok(())
1378    }
1379
1380    fn last_media(&mut self) -> Result<&mut MediaDescription> {
1381        self.desc
1382            .media_descriptions
1383            .last_mut()
1384            .ok_or(Error::SdpEmptyTimeDescription)
1385    }
1386
1387    /// `text = byte-string`.
1388    fn text(&self, what: &str, value: &str) -> Result<String> {
1389        if !(grammar::is_byte_string(value) || self.options.loose_fields) {
1390            return Err(syntax(what, value));
1391        }
1392        Ok(value.to_owned())
1393    }
1394
1395    /// `username SP sess-id SP sess-version SP nettype SP addrtype SP unicast-address`.
1396    fn origin(&self, value: &str) -> Result<Origin> {
1397        let fields = self.fields("o=", value)?;
1398        let [
1399            username,
1400            session_id,
1401            session_version,
1402            network_type,
1403            address_type,
1404            address,
1405        ] = fields[..]
1406        else {
1407            return Err(syntax("o=", value));
1408        };
1409        if !grammar::is_non_ws_string(username)
1410            || !grammar::is_token(network_type)
1411            || !grammar::is_token(address_type)
1412        {
1413            return Err(syntax("o=", value));
1414        }
1415        let address_ok = if self.options.loose_fields {
1416            grammar::is_non_ws_string(address)
1417        } else {
1418            grammar::is_unicast_address(address_type, address)
1419        };
1420        if !address_ok {
1421            return Err(syntax("o= unicast-address", value));
1422        }
1423        Ok(Origin {
1424            username: username.to_owned(),
1425            // The grammar has no upper bound (RFC 8866 section 9: `1*DIGIT`), and nor has
1426            // this type: RFC 9429 section 5.8 accepts compliant SDP beyond the 64 bits
1427            // section 5.2.1 generates.
1428            session_id: SdpDecimal::parse(session_id)
1429                .ok_or_else(|| syntax("o= sess-id", session_id))?,
1430            session_version: SdpDecimal::parse(session_version)
1431                .ok_or_else(|| syntax("o= sess-version", session_version))?,
1432            network_type: network_type.to_owned(),
1433            address_type: address_type.to_owned(),
1434            unicast_address: address.to_owned(),
1435        })
1436    }
1437
1438    fn connection(&self, value: &str) -> Result<ConnectionInformation> {
1439        let fields = self.fields("c=", value)?;
1440        if !self.options.loose_fields {
1441            return ConnectionInformation::parse_fields(&fields, value);
1442        }
1443        if !(2..=3).contains(&fields.len())
1444            || !grammar::is_token(fields[0])
1445            || !grammar::is_token(fields[1])
1446        {
1447            return Err(syntax("c=", value));
1448        }
1449        Ok(ConnectionInformation {
1450            network_type: fields[0].to_owned(),
1451            address_type: fields[1].to_owned(),
1452            address: fields.get(2).map(|address| {
1453                // Kept whole when it is not an address the grammar knows.
1454                Address::parse(fields[1], address).unwrap_or_else(|_| Address {
1455                    address: (*address).to_owned(),
1456                    ttl: None,
1457                    range: None,
1458                })
1459            }),
1460        })
1461    }
1462
1463    fn bandwidth(&self, value: &str) -> Result<Bandwidth> {
1464        if self.options.loose_fields {
1465            Bandwidth::parse(value.trim())
1466        } else {
1467            Bandwidth::parse(value)
1468        }
1469    }
1470
1471    /// `start-time SP stop-time`, each `time / "0"`, `time = POS-DIGIT 9*DIGIT`.
1472    fn timing(&self, value: &str) -> Result<Timing> {
1473        let fields = self.fields("t=", value)?;
1474        let loose = self.options.loose_fields;
1475        if fields.len() < 2 || (fields.len() > 2 && !loose) {
1476            return Err(syntax("t=", value));
1477        }
1478        let time = |field: &str| -> Result<u64> {
1479            if !(loose || field == "0" || (grammar::is_integer(field) && field.len() >= 10)) {
1480                return Err(syntax("t=", value));
1481            }
1482            grammar::digits("t=", field)
1483        };
1484        Ok(Timing {
1485            start_time: time(fields[0])?,
1486            stop_time: time(fields[1])?,
1487        })
1488    }
1489
1490    /// `repeat-interval SP typed-time 1*(SP typed-time)`.
1491    fn repeat(&self, value: &str) -> Result<RepeatTime> {
1492        let fields = self.fields("r=", value)?;
1493        if fields.len() < 3 {
1494            return Err(syntax("r=", value));
1495        }
1496        // repeat-interval = POS-DIGIT *DIGIT [fixed-len-time-unit]
1497        if fields[0].starts_with('0') {
1498            return Err(syntax("r= repeat-interval", value));
1499        }
1500        let interval = parse_typed_time(fields[0])?;
1501        let duration = parse_typed_time(fields[1])?;
1502        let mut offsets = Vec::with_capacity(fields.len() - 2);
1503        for field in &fields[2..] {
1504            offsets.push(parse_typed_time(field)?);
1505        }
1506        Ok(RepeatTime {
1507            interval,
1508            duration,
1509            offsets,
1510        })
1511    }
1512
1513    /// `time SP ["-"] typed-time *(SP time SP ["-"] typed-time)`.
1514    fn zones(&self, value: &str) -> Result<Vec<TimeZone>> {
1515        let fields = self.fields("z=", value)?;
1516        if !fields.len().is_multiple_of(2) {
1517            return Err(syntax("z=", value));
1518        }
1519        let mut zones = Vec::with_capacity(fields.len() / 2);
1520        for pair in fields.chunks(2) {
1521            let time = pair[0];
1522            if !(self.options.loose_fields || (grammar::is_integer(time) && time.len() >= 10)) {
1523                return Err(syntax("z= adjustment time", value));
1524            }
1525            let adjustment_time = grammar::digits("z= adjustment time", time)?;
1526            let offset = match pair[1].strip_prefix('-') {
1527                Some(positive) => parse_typed_time(positive)?
1528                    .checked_neg()
1529                    .ok_or_else(|| invalid("z= offset", value))?,
1530                None => parse_typed_time(pair[1])?,
1531            };
1532            zones.push(TimeZone {
1533                adjustment_time,
1534                offset,
1535            });
1536        }
1537        Ok(zones)
1538    }
1539
1540    /// `media SP port ["/" integer] SP proto 1*(SP fmt)`.
1541    fn media_line(&mut self, value: &str) -> Result<()> {
1542        if self.desc.media_descriptions.len() >= MAX_MEDIA_DESCRIPTIONS {
1543            return Err(over_limit("media sections", MAX_MEDIA_DESCRIPTIONS));
1544        }
1545
1546        let fields = self.fields("m=", value)?;
1547        if fields.len() < 4 {
1548            return Err(syntax("m=", value));
1549        }
1550        if fields.len() - 3 > MAX_FORMATS_PER_MEDIA {
1551            return Err(over_limit("formats on one m= line", MAX_FORMATS_PER_MEDIA));
1552        }
1553
1554        // <media>
1555        // RFC 8866 section 5.14: <media> is a token ("audio", "video", "text",
1556        // "application", "message", "image" are registered, and new media types
1557        // may be), so an unknown one is parsed: it is the offer/answer layer that
1558        // rejects a media type it doesn't know (RFC 9429 section 5.3.1 answers
1559        // it with port 0), not the parser.
1560        if !grammar::is_token(fields[0]) {
1561            return Err(Error::SdpInvalidValue(fields[0].to_owned()));
1562        }
1563
1564        // <port> ["/" integer]
1565        let (port, count) = match fields[1].split_once('/') {
1566            Some((port, count)) => (port, Some(count)),
1567            None => (fields[1], None),
1568        };
1569        let port_value = grammar::port(port)? as isize;
1570        let port_range = match count {
1571            Some(count) => {
1572                if !grammar::is_integer(count) {
1573                    return Err(syntax("m= number of ports", value));
1574                }
1575                Some(
1576                    count
1577                        .parse::<u16>()
1578                        .map_err(|_| invalid("m= number of ports", value))?
1579                        as isize,
1580                )
1581            }
1582            None => None,
1583        };
1584
1585        // <proto>
1586        // RFC 8866 section 5.14: <proto> is the media transport protocol and is
1587        // extensible -- "New transport protocols MAY be defined, and MUST be
1588        // registered with IANA." Any `token *("/" token)` is accepted instead of a fixed
1589        // list, so IANA-registered transports beyond the RTP/SAVPF set interoperate, e.g.
1590        // UDP/BFCP (RFC 8856), TCP/DTLS/SCTP (RFC 8841) or TCP/MRCPv2.
1591        let mut protos = vec![];
1592        for proto in fields[2].split('/') {
1593            if !grammar::is_token(proto) {
1594                return Err(Error::SdpInvalidValue(fields[2].to_owned()));
1595            }
1596            protos.push(proto.to_owned());
1597        }
1598
1599        // <fmt>...
1600        let mut formats = Vec::with_capacity(fields.len() - 3);
1601        for field in &fields[3..] {
1602            if !grammar::is_token(field) {
1603                return Err(syntax("m= fmt", value));
1604            }
1605            formats.push((*field).to_owned());
1606        }
1607
1608        self.desc.media_descriptions.push(MediaDescription {
1609            media_name: MediaName {
1610                media: fields[0].to_owned(),
1611                port: RangedPort {
1612                    value: port_value,
1613                    range: port_range,
1614                },
1615                protos,
1616                formats,
1617            },
1618            media_title: None,
1619            connection_information: None,
1620            bandwidth: vec![],
1621            encryption_key: None,
1622            attributes: vec![],
1623        });
1624        Ok(())
1625    }
1626}
1627
1628/// `attribute = (attribute-name ":" attribute-value) / attribute-name`, the name a token.
1629///
1630/// The value starts after the first colon and is kept whole.
1631pub(crate) fn parse_attribute(value: &str) -> Result<Attribute> {
1632    let (key, value) = match value.split_once(':') {
1633        Some((key, value)) => (key, Some(value)),
1634        None => (value, None),
1635    };
1636    if !grammar::is_token(key) {
1637        return Err(syntax("attribute name", key));
1638    }
1639    Ok(Attribute {
1640        key: key.to_owned(),
1641        value: value.map(str::to_owned),
1642    })
1643}
1644
1645/// `key-type = "prompt" / "clear:" text / "base64:" base64 / "uri:" uri`. The line is
1646/// obsolete and its content is not kept (RFC 8866 section 5.12).
1647fn check_key(value: &str) -> Result<()> {
1648    let ok = if value == "prompt" {
1649        true
1650    } else if let Some(text) = value.strip_prefix("clear:") {
1651        grammar::is_byte_string(text)
1652    } else if let Some(key) = value.strip_prefix("base64:") {
1653        grammar::is_base64(key)
1654    } else if let Some(uri) = value.strip_prefix("uri:") {
1655        grammar::is_non_ws_string(uri)
1656    } else {
1657        false
1658    };
1659    if ok {
1660        Ok(())
1661    } else {
1662        // The key is not quoted in the error: it may be one.
1663        Err(Error::SdpInvalidSyntax("k= line".to_owned()))
1664    }
1665}
1666
1667/// `email-safe`: any byte except NUL, CR, LF and the quoting characters `()<>`.
1668fn is_email_safe(value: &str) -> bool {
1669    !value.is_empty()
1670        && !value
1671            .bytes()
1672            .any(|b| matches!(b, 0 | b'\r' | b'\n' | b'(' | b')' | b'<' | b'>'))
1673}
1674
1675/// RFC 5322 `atext`.
1676fn is_atext(b: u8) -> bool {
1677    b.is_ascii_alphanumeric() || b"!#$%&'*+-/=?^_`{|}~".contains(&b)
1678}
1679
1680/// RFC 5322 `dot-atom-text = 1*atext *("." 1*atext)`.
1681fn is_dot_atom(value: &str) -> bool {
1682    !value.is_empty()
1683        && value
1684            .split('.')
1685            .all(|atom| !atom.is_empty() && atom.bytes().all(is_atext))
1686}
1687
1688/// RFC 5322 `addr-spec = local-part "@" domain`, without comments, folding white space or
1689/// the obsolete forms: the local part is a dot-atom or a quoted string, the domain a
1690/// dot-atom or a domain literal.
1691fn is_addr_spec(value: &str) -> bool {
1692    let bytes = value.as_bytes();
1693    let at = if bytes.first() == Some(&b'"') {
1694        // quoted-string: DQUOTE *(qtext / quoted-pair / WSP) DQUOTE
1695        let mut i = 1;
1696        loop {
1697            match bytes.get(i) {
1698                Some(b'"') => break i + 1,
1699                Some(b'\\') if matches!(bytes.get(i + 1), Some(0x20..=0x7e | b'\t')) => i += 2,
1700                Some(b' ' | b'\t' | 0x21 | 0x23..=0x5b | 0x5d..=0x7e) => i += 1,
1701                _ => return false,
1702            }
1703        }
1704    } else {
1705        match value.find('@') {
1706            Some(at) if is_dot_atom(&value[..at]) => at,
1707            _ => return false,
1708        }
1709    };
1710    if bytes.get(at) != Some(&b'@') {
1711        return false;
1712    }
1713    let domain = &value[at + 1..];
1714    match domain.strip_prefix('[').and_then(|d| d.strip_suffix(']')) {
1715        // domain-literal: "[" *dtext "]"
1716        Some(literal) => literal
1717            .bytes()
1718            .all(|b| matches!(b, 0x21..=0x5a | 0x5e..=0x7e)),
1719        None => is_dot_atom(domain),
1720    }
1721}
1722
1723/// `email-address = address-and-comment / dispname-and-address / addr-spec`.
1724fn is_email_address(value: &str) -> bool {
1725    if let Some(rest) = value.strip_suffix(')') {
1726        // addr-spec 1*SP "(" 1*email-safe ")"
1727        let Some((address, comment)) = rest.split_once('(') else {
1728            return false;
1729        };
1730        let spec = address.trim_end_matches(' ');
1731        return spec.len() < address.len() && is_addr_spec(spec) && is_email_safe(comment);
1732    }
1733    if let Some(rest) = value.strip_suffix('>') {
1734        // 1*email-safe 1*SP "<" addr-spec ">"
1735        let Some((name, address)) = rest.split_once('<') else {
1736            return false;
1737        };
1738        return name.ends_with(' ')
1739            && is_email_safe(name.trim_end_matches(' '))
1740            && is_addr_spec(address);
1741    }
1742    is_addr_spec(value)
1743}
1744
1745/// `phone = ["+"] DIGIT 1*(SP / "-" / DIGIT)`.
1746fn is_phone(value: &str) -> bool {
1747    let digits = value.strip_prefix('+').unwrap_or(value).as_bytes();
1748    digits.len() >= 2
1749        && digits[0].is_ascii_digit()
1750        && digits[1..]
1751            .iter()
1752            .all(|b| b.is_ascii_digit() || *b == b' ' || *b == b'-')
1753}
1754
1755/// `phone-number = phone *SP "(" 1*email-safe ")" / 1*email-safe "<" phone ">" / phone`.
1756fn is_phone_number(value: &str) -> bool {
1757    if let Some(rest) = value.strip_suffix(')') {
1758        let Some((phone, comment)) = rest.split_once('(') else {
1759            return false;
1760        };
1761        // `phone` itself may end in spaces: `*SP` adds nothing to check.
1762        return is_phone(phone) && is_email_safe(comment);
1763    }
1764    if let Some(rest) = value.strip_suffix('>') {
1765        let Some((name, phone)) = rest.split_once('<') else {
1766            return false;
1767        };
1768        return is_email_safe(name) && is_phone(phone);
1769    }
1770    is_phone(value)
1771}
1772
1773/// `typed-time = 1*DIGIT [fixed-len-time-unit]`, in seconds.
1774///
1775/// The units are `d`, `h`, `m` and `s`, case-sensitive.
1776fn parse_typed_time(value: &str) -> Result<i64> {
1777    let (number, factor) = match value.as_bytes().last() {
1778        Some(b'd') => (&value[..value.len() - 1], 86400),
1779        Some(b'h') => (&value[..value.len() - 1], 3600),
1780        Some(b'm') => (&value[..value.len() - 1], 60),
1781        Some(b's') => (&value[..value.len() - 1], 1),
1782        _ => (value, 1),
1783    };
1784    grammar::digits::<i64>("typed-time", number)?
1785        .checked_mul(factor)
1786        .ok_or_else(|| invalid("typed-time", value))
1787}