Skip to main content

rtci_sdp/attribute/
simulcast.rs

1//! `a=rid` (RFC 8851) and `a=simulcast` (RFC 8853, with the pause marker of RFC 7728).
2
3use std::fmt;
4
5use shared::error::Result;
6
7use super::TypedAttribute;
8use crate::grammar::{self, invalid, syntax};
9
10/// `rid-dir`: which way the restrictions of an `a=rid` line apply.
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
12pub enum RidDirection {
13    /// `send`
14    Send,
15    /// `recv`
16    Recv,
17}
18
19impl RidDirection {
20    fn parse(value: &str) -> Option<Self> {
21        match value {
22            "send" => Some(RidDirection::Send),
23            "recv" => Some(RidDirection::Recv),
24            _ => None,
25        }
26    }
27
28    fn as_str(self) -> &'static str {
29        match self {
30            RidDirection::Send => "send",
31            RidDirection::Recv => "recv",
32        }
33    }
34}
35
36impl fmt::Display for RidDirection {
37    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38        f.write_str(self.as_str())
39    }
40}
41
42/// The `rid-id` grammar a line is read with.
43///
44/// RFC 8851 section 10 as published has `rid-id = 1*(alpha-numeric / "-" / "_")`; erratum
45/// 7132 (Verified 2022-10-13) corrects it to `rid-id = 1*255(alpha-numeric)`, "consistent with
46/// the rules for the RtpStreamId/RepairedRtpStreamId SDES from RFC 8852 section 3". The
47/// corrected grammar is the default; [`Rid::parse`], [`Simulcast::parse`] and [`Rid::new`]
48/// use it.
49#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
50pub enum RidIdGrammar {
51    /// `1*255(alpha-numeric)` (erratum 7132).
52    #[default]
53    Corrected,
54    /// `1*(alpha-numeric / "-" / "_")`, of any length: RFC 8851 as published.
55    Published,
56}
57
58impl RidIdGrammar {
59    /// Whether `id` is a rid-id in this grammar.
60    pub fn admits(self, id: &str) -> bool {
61        match self {
62            RidIdGrammar::Corrected => grammar::is_rid_id(id),
63            RidIdGrammar::Published => grammar::is_alnum_dash_underscore(id),
64        }
65    }
66}
67
68/// The restrictions whose value is `int-param-val = 1*DIGIT`.
69const RID_INTEGER_RESTRICTIONS: [&str; 6] = [
70    "max-width",
71    "max-height",
72    "max-fps",
73    "max-fs",
74    "max-br",
75    "max-pps",
76];
77
78/// `a=rid:<rid-id> <direction> [pt=<fmt-list>;]<restriction>=<value>;...` (RFC 8851
79/// section 10).
80///
81/// ```text
82/// rid-syntax        = %s"a=rid:" rid-id SP rid-dir [ rid-pt-param-list / rid-param-list ]
83/// rid-id            = 1*255(alpha-numeric)        ; erratum 7132 (see RidIdGrammar)
84/// rid-pt-param-list = SP rid-fmt-list *(";" rid-param)
85/// rid-param-list    = SP rid-param *(";" rid-param)
86/// rid-fmt-list      = %s"pt=" fmt *( "," fmt )
87/// ```
88///
89/// The restrictions RFC 8851 section 5 defines have accessors (`max_width()` and the
90/// others); any other `name[=value]` is kept in [`Rid::restrictions`], in the order
91/// written, so that it can be recognised or refused by whoever knows it (section 6.2: an
92/// answerer discards an `a=rid` line with a restriction it does not understand).
93#[derive(Debug, Clone, PartialEq, Eq)]
94pub struct Rid {
95    /// The RTP stream identifier: 1 to 255 letters and digits (`-` and `_` too, and any
96    /// length, when read with [`RidIdGrammar::Published`]).
97    pub id: String,
98    /// The direction the restrictions apply in.
99    pub direction: RidDirection,
100    /// The `pt=` list: the payload types the stream may use. Empty when there is no `pt=`,
101    /// which means any payload type of the media section.
102    pub formats: Vec<u8>,
103    /// Every restriction but `pt=`, as `(name, value)`, in order. No name occurs twice.
104    pub restrictions: Vec<(String, Option<String>)>,
105}
106
107impl Rid {
108    /// An `a=rid` line with no `pt=` and no restriction. `id` must be a rid-id of the
109    /// corrected grammar ([`RidIdGrammar::Corrected`]).
110    pub fn new(id: impl Into<String>, direction: RidDirection) -> Result<Self> {
111        Self::new_in(id, direction, RidIdGrammar::Corrected)
112    }
113
114    fn new_in(
115        id: impl Into<String>,
116        direction: RidDirection,
117        rid_ids: RidIdGrammar,
118    ) -> Result<Self> {
119        let id = id.into();
120        if !rid_ids.admits(&id) {
121            return Err(syntax("rid-id", &id));
122        }
123        Ok(Rid {
124            id,
125            direction,
126            formats: vec![],
127            restrictions: vec![],
128        })
129    }
130
131    /// The value of the restriction `name`. The outer `None` is "not present"; the inner
132    /// one is "present without a value".
133    pub fn restriction(&self, name: &str) -> Option<Option<&str>> {
134        self.restrictions
135            .iter()
136            .find(|(n, _)| n == name)
137            .map(|(_, v)| v.as_deref())
138    }
139
140    fn integer(&self, name: &str) -> Option<u64> {
141        // Checked when the line was parsed; a hand-built one that does not parse is absent.
142        self.restriction(name)??.parse().ok()
143    }
144
145    /// `max-width`, in pixels.
146    pub fn max_width(&self) -> Option<u64> {
147        self.integer("max-width")
148    }
149
150    /// `max-height`, in pixels.
151    pub fn max_height(&self) -> Option<u64> {
152        self.integer("max-height")
153    }
154
155    /// `max-fps`, in frames per second.
156    pub fn max_fps(&self) -> Option<u64> {
157        self.integer("max-fps")
158    }
159
160    /// `max-fs`, the frame size in pixels per frame.
161    pub fn max_fs(&self) -> Option<u64> {
162        self.integer("max-fs")
163    }
164
165    /// `max-br`, in bits per second.
166    pub fn max_br(&self) -> Option<u64> {
167        self.integer("max-br")
168    }
169
170    /// `max-pps`, in pixels per second.
171    pub fn max_pps(&self) -> Option<u64> {
172        self.integer("max-pps")
173    }
174
175    /// `max-bpp`, in bits per pixel.
176    pub fn max_bpp(&self) -> Option<f64> {
177        self.restriction("max-bpp")??.parse().ok()
178    }
179
180    /// `depend`: the rid-ids this stream depends on. Empty when there is none.
181    pub fn depend(&self) -> Vec<&str> {
182        match self.restriction("depend") {
183            Some(Some(list)) => list.split(',').collect(),
184            _ => vec![],
185        }
186    }
187}
188
189/// `float-param-val = 1*DIGIT "." 1*DIGIT`.
190fn is_float_param(value: &str) -> bool {
191    matches!(value.split_once('.'), Some((i, f)) if grammar::is_digits(i) && grammar::is_digits(f))
192}
193
194/// `param-val = *(%x20-3A / %x3C-7E)`: printable, no semicolon.
195fn is_param_val(value: &str) -> bool {
196    value
197        .bytes()
198        .all(|b| (0x20..=0x7e).contains(&b) && b != b';')
199}
200
201impl TypedAttribute for Rid {
202    const NAME: &'static str = "rid";
203
204    /// The line read with the corrected `rid-id` grammar ([`RidIdGrammar::Corrected`]).
205    fn parse(value: &str) -> Result<Self> {
206        Rid::parse_with(value, RidIdGrammar::Corrected)
207    }
208}
209
210impl Rid {
211    /// The value of an `a=rid` line, its rid-ids (its own and `depend=`'s) read with
212    /// `rid_ids`.
213    pub fn parse_with(value: &str, rid_ids: RidIdGrammar) -> Result<Self> {
214        let mut parts = value.splitn(3, ' ');
215        let (Some(id), Some(direction)) = (parts.next(), parts.next()) else {
216            return Err(syntax("a=rid", value));
217        };
218        let Some(direction) = RidDirection::parse(direction) else {
219            return Err(syntax("a=rid direction", value));
220        };
221        let mut rid = Rid::new_in(id, direction, rid_ids).map_err(|_| syntax("a=rid", value))?;
222
223        let Some(params) = parts.next() else {
224            return Ok(rid);
225        };
226        for (index, param) in params.split(';').enumerate() {
227            let (name, param_value) = match param.split_once('=') {
228                Some((name, v)) => (name, Some(v)),
229                None => (param, None),
230            };
231            if name.is_empty() || !name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-') {
232                return Err(syntax("a=rid restriction", value));
233            }
234
235            if name == "pt" {
236                // rid-fmt-list is the first parameter, and needs a value.
237                let Some(list) = param_value.filter(|_| index == 0) else {
238                    return Err(syntax("a=rid pt", value));
239                };
240                for fmt in list.split(',') {
241                    let pt: u8 = grammar::digits_no_leading_zero("a=rid pt", fmt)?;
242                    if pt > 127 || rid.formats.contains(&pt) {
243                        return Err(invalid("a=rid pt", value));
244                    }
245                    rid.formats.push(pt);
246                }
247                continue;
248            }
249
250            let ok = match (name, param_value) {
251                (n, v) if RID_INTEGER_RESTRICTIONS.contains(&n) => v.is_none_or(grammar::is_digits),
252                ("max-bpp", v) => v.is_none_or(is_float_param),
253                // rid-depend-param = %s"depend=" rid-list
254                ("depend", Some(list)) => list.split(',').all(|id| rid_ids.admits(id)),
255                ("depend", None) => false,
256                (_, v) => v.is_none_or(is_param_val),
257            };
258            if !ok {
259                return Err(syntax("a=rid restriction", value));
260            }
261            if rid.restriction(name).is_some() {
262                return Err(invalid("a=rid: a restriction occurs twice", value));
263            }
264            rid.restrictions
265                .push((name.to_owned(), param_value.map(str::to_owned)));
266        }
267        Ok(rid)
268    }
269}
270
271impl fmt::Display for Rid {
272    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
273        write!(f, "{} {}", self.id, self.direction)?;
274        let mut separator = ' ';
275        if !self.formats.is_empty() {
276            write!(f, " pt=")?;
277            for (i, pt) in self.formats.iter().enumerate() {
278                if i > 0 {
279                    f.write_str(",")?;
280                }
281                write!(f, "{pt}")?;
282            }
283            separator = ';';
284        }
285        for (name, value) in &self.restrictions {
286            write!(f, "{separator}{name}")?;
287            if let Some(value) = value {
288                write!(f, "={value}")?;
289            }
290            separator = ';';
291        }
292        Ok(())
293    }
294}
295
296/// One `sc-id` of an `a=simulcast` line: a rid-id, with `~` in front when the stream is
297/// initially paused (RFC 8853 section 5.1, RFC 7728).
298#[derive(Debug, Clone, PartialEq, Eq, Hash)]
299pub struct SimulcastId {
300    /// The rid-id, naming an `a=rid` line of the same media section.
301    pub rid: String,
302    /// Whether the stream starts paused (`~`).
303    pub paused: bool,
304}
305
306impl fmt::Display for SimulcastId {
307    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
308        if self.paused {
309            f.write_str("~")?;
310        }
311        f.write_str(&self.rid)
312    }
313}
314
315/// `a=simulcast:<direction> <streams> [<direction> <streams>]` (RFC 8853 section 5.1).
316///
317/// ```text
318/// sc-value     = ( sc-send [SP sc-recv] ) / ( sc-recv [SP sc-send] )
319/// sc-send      = %s"send" SP sc-str-list
320/// sc-recv      = %s"recv" SP sc-str-list
321/// sc-str-list  = sc-alt-list *( ";" sc-alt-list )
322/// sc-alt-list  = sc-id *( "," sc-id )
323/// sc-id        = [sc-id-paused] rid-id
324/// ```
325///
326/// A direction is a list of simulcast streams, separated by `;`; a stream is a list of
327/// alternative formats, separated by `,`, of which one is used at a time. A rid-id occurs
328/// once in the whole attribute (section 5.2).
329#[derive(Debug, Clone, PartialEq, Eq, Default)]
330pub struct Simulcast {
331    /// The streams sent: one entry per stream, each a list of alternatives. Empty when the
332    /// attribute has no `send` part.
333    pub send: Vec<Vec<SimulcastId>>,
334    /// The streams received, likewise.
335    pub recv: Vec<Vec<SimulcastId>>,
336    /// Whether `recv` was written before `send`. Both orders mean the same.
337    pub recv_first: bool,
338}
339
340impl Simulcast {
341    /// Every rid-id of the attribute, `send` first.
342    pub fn rids(&self) -> impl Iterator<Item = &str> {
343        self.send
344            .iter()
345            .chain(&self.recv)
346            .flatten()
347            .map(|id| id.rid.as_str())
348    }
349}
350
351fn parse_stream_list(
352    value: &str,
353    list: &str,
354    rid_ids: RidIdGrammar,
355) -> Result<Vec<Vec<SimulcastId>>> {
356    list.split(';')
357        .map(|alternatives| {
358            alternatives
359                .split(',')
360                .map(|id| {
361                    let (rid, paused) = match id.strip_prefix('~') {
362                        Some(rid) => (rid, true),
363                        None => (id, false),
364                    };
365                    if !rid_ids.admits(rid) {
366                        return Err(syntax("a=simulcast", value));
367                    }
368                    Ok(SimulcastId {
369                        rid: rid.to_owned(),
370                        paused,
371                    })
372                })
373                .collect()
374        })
375        .collect()
376}
377
378impl TypedAttribute for Simulcast {
379    const NAME: &'static str = "simulcast";
380
381    /// The line read with the corrected `rid-id` grammar ([`RidIdGrammar::Corrected`]).
382    fn parse(value: &str) -> Result<Self> {
383        Simulcast::parse_with(value, RidIdGrammar::Corrected)
384    }
385}
386
387impl Simulcast {
388    /// The value of an `a=simulcast` line, its rid-ids read with `rid_ids`.
389    pub fn parse_with(value: &str, rid_ids: RidIdGrammar) -> Result<Self> {
390        let fields = grammar::fields("a=simulcast", value)?;
391        if fields.len() != 2 && fields.len() != 4 {
392            return Err(syntax("a=simulcast", value));
393        }
394        let mut simulcast = Simulcast::default();
395        for (index, pair) in fields.chunks(2).enumerate() {
396            let list = parse_stream_list(value, pair[1], rid_ids)?;
397            let slot = match RidDirection::parse(pair[0]) {
398                Some(RidDirection::Send) => &mut simulcast.send,
399                Some(RidDirection::Recv) => {
400                    simulcast.recv_first = index == 0;
401                    &mut simulcast.recv
402                }
403                None => return Err(syntax("a=simulcast direction", value)),
404            };
405            // "each direction MUST NOT occur more than once on the same line"
406            if !slot.is_empty() {
407                return Err(syntax("a=simulcast: a direction occurs twice", value));
408            }
409            *slot = list;
410        }
411        // "a single rid-id MUST NOT occur more than once per 'a=simulcast' line"
412        let mut seen: Vec<&str> = Vec::new();
413        for rid in simulcast.rids() {
414            if seen.contains(&rid) {
415                return Err(invalid("a=simulcast: a rid-id occurs twice", value));
416            }
417            seen.push(rid);
418        }
419        Ok(simulcast)
420    }
421}
422
423fn write_stream_list(f: &mut fmt::Formatter<'_>, streams: &[Vec<SimulcastId>]) -> fmt::Result {
424    for (i, alternatives) in streams.iter().enumerate() {
425        if i > 0 {
426            f.write_str(";")?;
427        }
428        for (j, id) in alternatives.iter().enumerate() {
429            if j > 0 {
430                f.write_str(",")?;
431            }
432            write!(f, "{id}")?;
433        }
434    }
435    Ok(())
436}
437
438impl fmt::Display for Simulcast {
439    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
440        let send = (RidDirection::Send, &self.send);
441        let recv = (RidDirection::Recv, &self.recv);
442        let order = if self.recv_first {
443            [recv, send]
444        } else {
445            [send, recv]
446        };
447        let mut first = true;
448        for (direction, streams) in order {
449            if streams.is_empty() {
450                continue;
451            }
452            if !first {
453                f.write_str(" ")?;
454            }
455            first = false;
456            write!(f, "{direction} ")?;
457            write_stream_list(f, streams)?;
458        }
459        Ok(())
460    }
461}