Skip to main content

rtci_sdp/extmap/
mod.rs

1//! `a=extmap` RTP header-extension declarations.
2//!
3//! An [`ExtMap`](crate::extmap::ExtMap) binds a header-extension URI to the small integer id that will appear in RTP
4//! packets. Both sides must agree, which is the whole point of negotiating it in SDP: the id is
5//! per-session, while the URI is the stable name.
6//!
7//! The `*_URI` constants are the extensions this stack uses — audio level, video orientation,
8//! absolute send time, transport-wide CC, and the SDES ids that make simulcast demultiplexing
9//! possible.
10#[cfg(test)]
11mod extmap_test;
12
13use super::direction::*;
14use crate::attribute::TypedAttribute;
15use crate::description::common::*;
16use crate::grammar;
17use shared::error::{Error, Result};
18
19use std::fmt;
20use std::io;
21use url::Url;
22
23/// Default ext values
24pub const DEF_EXT_MAP_VALUE_ABS_SEND_TIME: usize = 1;
25/// The default id this crate assigns to the transport-wide CC extension.
26pub const DEF_EXT_MAP_VALUE_TRANSPORT_CC: usize = 2;
27/// The default id assigned to the SDES `mid` extension.
28pub const DEF_EXT_MAP_VALUE_SDES_MID: usize = 3;
29/// The default id assigned to the SDES RTP stream id extension.
30pub const DEF_EXT_MAP_VALUE_SDES_RTP_STREAM_ID: usize = 4;
31
32/// The absolute-send-time extension URI, used for bandwidth estimation.
33pub const ABS_SEND_TIME_URI: &str = "http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time";
34/// The transport-wide congestion control extension URI.
35pub const TRANSPORT_CC_URI: &str =
36    "http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01";
37/// The SDES `mid` extension URI, which tags each packet with its m-line.
38pub const SDES_MID_URI: &str = "urn:ietf:params:rtp-hdrext:sdes:mid";
39/// The SDES RTP stream id (RID) extension URI, which identifies a simulcast layer.
40pub const SDES_RTP_STREAM_ID_URI: &str = "urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id";
41/// The SDES repaired RTP stream id extension URI, which identifies an RTX layer's target.
42pub const SDES_REPAIR_RTP_STREAM_ID_URI: &str =
43    "urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id";
44
45/// The audio-level extension URI, carrying per-packet loudness.
46pub const AUDIO_LEVEL_URI: &str = "urn:ietf:params:rtp-hdrext:ssrc-audio-level";
47/// The video-orientation (CVO) extension URI, carrying rotation flags.
48pub const VIDEO_ORIENTATION_URI: &str = "urn:3gpp:video-orientation";
49
50/// The first of the ids an offerer uses for an extension it leaves the answerer to number
51/// (RFC 8285 section 6).
52pub const EXT_MAP_ANSWERER_ASSIGNED_MIN: u16 = 4096;
53/// The last of those ids.
54pub const EXT_MAP_ANSWERER_ASSIGNED_MAX: u16 = 4351;
55
56/// ExtMap represents the activation of a single RTP header extension:
57/// `a=extmap:<value>["/"<direction>] <URI> [<extensionattributes>]` (RFC 8285 section 5).
58///
59/// ```text
60/// extmap-value        = mapentry SP extensionname [SP extensionattributes]
61/// mapentry            = "extmap:" 1*5DIGIT ["/" direction]
62/// extensionname       = URI
63/// extensionattributes = byte-string
64/// direction           = "sendonly" / "recvonly" / "sendrecv" / "inactive"
65/// ```
66#[derive(Debug, Clone, Default)]
67pub struct ExtMap {
68    /// The id this extension is negotiated under.
69    ///
70    /// RFC 8285 section 4.3 calls 1 to 256 the valid range: 1 to 255 is the local identifier
71    /// that appears in RTP packets (1 to 14 fit the one-byte header form; 15 and above need
72    /// the two-byte form), and 256 names the four `appbits` of the two-byte header. 4096 to
73    /// 4351 is not an identifier: an offerer with more extensions than identifiers, or with
74    /// alternatives, uses that range, and the answerer that wants the extension remaps it
75    /// to a free valid id (RFC 8285 section 6). See [`ExtMap::is_answerer_assigned`].
76    pub value: u16,
77    /// The direction the extension applies in, if the attribute restricted it.
78    pub direction: Direction,
79    /// The extension's canonical URI.
80    pub uri: Option<Url>,
81    /// Extension-specific attributes trailing the URI: a byte-string, spaces included.
82    pub ext_attr: Option<String>,
83}
84
85impl fmt::Display for ExtMap {
86    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
87        write!(f, "{}", self.value)?;
88
89        if self.direction != Direction::Unspecified {
90            write!(f, "/{}", self.direction)?;
91        }
92
93        if let Some(uri) = &self.uri {
94            write!(f, " {uri}")?;
95        }
96
97        if let Some(ext_attr) = &self.ext_attr {
98            write!(f, " {ext_attr}")?;
99        }
100
101        Ok(())
102    }
103}
104
105impl TypedAttribute for ExtMap {
106    const NAME: &'static str = "extmap";
107
108    /// Parses the value of an `a=extmap` line: what follows `extmap:`.
109    ///
110    /// The id must be one RFC 8285 gives a meaning: 1 to 256 (the valid range), or 4096 to
111    /// 4351 (the range an answerer remaps). 0 is padding, and nothing else is defined.
112    fn parse(value: &str) -> Result<Self> {
113        let error = || Error::ParseExtMap(value.to_owned());
114
115        let (entry, rest) = value.split_once(' ').ok_or_else(error)?;
116        let (uri, ext_attr) = match rest.split_once(' ') {
117            Some((uri, ext_attr)) => (uri, Some(ext_attr)),
118            None => (rest, None),
119        };
120        if uri.is_empty() || ext_attr.is_some_and(|a| !grammar::is_byte_string(a)) {
121            return Err(error());
122        }
123
124        let (id, direction) = match entry.split_once('/') {
125            Some((id, direction)) => (id, Some(direction)),
126            None => (entry, None),
127        };
128        // mapentry = "extmap:" 1*5DIGIT
129        if !grammar::is_digits(id) || id.len() > 5 {
130            return Err(error());
131        }
132        let value_id = id.parse::<u32>().map_err(|_| error())?;
133        let in_range = (1..=256).contains(&value_id)
134            || (EXT_MAP_ANSWERER_ASSIGNED_MIN as u32..=EXT_MAP_ANSWERER_ASSIGNED_MAX as u32)
135                .contains(&value_id);
136        if !in_range {
137            return Err(Error::ParseExtMap(format!(
138                "{id} -- extmap key must be in the range 1-256 or 4096-4351"
139            )));
140        }
141
142        let direction = match direction {
143            None => Direction::Unspecified,
144            Some(direction) => match Direction::new(direction) {
145                Direction::Unspecified => {
146                    return Err(Error::ParseExtMap(format!(
147                        "unknown direction from {direction}"
148                    )));
149                }
150                direction => direction,
151            },
152        };
153
154        Ok(ExtMap {
155            value: value_id as u16,
156            direction,
157            uri: Some(Url::parse(uri)?),
158            ext_attr: ext_attr.map(str::to_owned),
159        })
160    }
161}
162
163impl ExtMap {
164    /// converts this object to an Attribute
165    pub fn convert(&self) -> Attribute {
166        Attribute {
167            key: "extmap".to_string(),
168            value: Some(self.to_string()),
169        }
170    }
171
172    /// Whether the id is in the 4096 to 4351 range: the offerer did not number the
173    /// extension, and an answerer that accepts it remaps it to a free id in the valid range
174    /// (RFC 8285 section 6). Such an id never appears in a packet.
175    pub fn is_answerer_assigned(&self) -> bool {
176        (EXT_MAP_ANSWERER_ASSIGNED_MIN..=EXT_MAP_ANSWERER_ASSIGNED_MAX).contains(&self.value)
177    }
178
179    /// Whether the id fits the one-byte header form (1 to 14). An id of 15 to 255 needs the
180    /// two-byte form (RFC 8285 section 4.3).
181    pub fn fits_one_byte_header(&self) -> bool {
182        (1..=14).contains(&self.value)
183    }
184
185    /// Whether the id identifies an extension element in a packet: 1 to 255. 256 (the
186    /// `appbits`) and the 4096 to 4351 range do not.
187    pub fn is_element_id(&self) -> bool {
188        (1..=255).contains(&self.value)
189    }
190
191    /// unmarshal creates an Extmap from a line of the form `extmap:<value>...` (the
192    /// attribute, with or without its `a=`), for a caller that will use the id in packets.
193    ///
194    /// It accepts what [`TypedAttribute::parse`] accepts, minus the ids that do not
195    /// identify an extension element: 256 (the `appbits`) and 4096 to 4351 (extensions the
196    /// offerer left for the answerer to number) are refused here, because every caller of
197    /// this function takes [`ExtMap::value`] as the identifier to put in, or look for in,
198    /// an RTP header. A caller that handles those ids (RFC 8285 section 6: skip the
199    /// extension, or remap it to a free id) parses with [`TypedAttribute::parse`], or
200    /// reads a description's `extmaps()`, and asks [`ExtMap::is_element_id`].
201    pub fn unmarshal<R: io::BufRead>(reader: &mut R) -> Result<Self> {
202        let mut line = String::new();
203        reader.read_line(&mut line)?;
204        let line = line.strip_suffix('\n').unwrap_or(&line);
205        let line = line.strip_suffix('\r').unwrap_or(line);
206        let parsed = match line.split_once(':') {
207            Some(("extmap" | "a=extmap", value)) => <Self as TypedAttribute>::parse(value)?,
208            _ => return Err(Error::ParseExtMap(line.to_owned())),
209        };
210        if !parsed.is_element_id() {
211            return Err(Error::ParseExtMap(format!(
212                "{} -- extmap key is not a local identifier (1-255)",
213                parsed.value
214            )));
215        }
216        Ok(parsed)
217    }
218
219    /// marshal creates a string from an ExtMap
220    pub fn marshal(&self) -> String {
221        "extmap:".to_string() + self.to_string().as_str()
222    }
223}