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