Skip to main content

rtci_sdp/attribute/
rtcp.rs

1//! `a=rtcp` (RFC 3605), `a=rtcp-fb` (RFC 4585, RFC 5104 and later) and `a=rtcp-xr`
2//! (RFC 3611).
3
4use std::fmt;
5
6use shared::error::Result;
7
8use super::TypedAttribute;
9use crate::description::common::Address;
10use crate::grammar::{self, invalid, syntax};
11
12/// `a=rtcp:<port> [<nettype> <addrtype> <connection-address>]` (RFC 3605 section 2.1): the
13/// port, and optionally the address, RTCP is sent to when it is not the one after the RTP
14/// port.
15#[derive(Debug, Clone, PartialEq, Eq)]
16pub struct Rtcp {
17    /// The RTCP port.
18    pub port: u16,
19    /// The RTCP address, when the line gives one.
20    pub address: Option<RtcpAddress>,
21}
22
23/// The address of an `a=rtcp` line.
24#[derive(Debug, Clone, PartialEq, Eq)]
25pub struct RtcpAddress {
26    /// The network type, `IN`.
27    pub network_type: String,
28    /// The address type, `IP4` or `IP6`.
29    pub address_type: String,
30    /// The address.
31    pub address: String,
32}
33
34impl TypedAttribute for Rtcp {
35    const NAME: &'static str = "rtcp";
36
37    fn parse(value: &str) -> Result<Self> {
38        let fields = grammar::fields("a=rtcp", value)?;
39        let address = match fields[1..] {
40            [] => None,
41            [network_type, address_type, address] => {
42                if !grammar::is_token(network_type) || !grammar::is_token(address_type) {
43                    return Err(syntax("a=rtcp", value));
44                }
45                // The same connection-address as a c= line.
46                Address::parse(address_type, address)?;
47                Some(RtcpAddress {
48                    network_type: network_type.to_owned(),
49                    address_type: address_type.to_owned(),
50                    address: address.to_owned(),
51                })
52            }
53            _ => return Err(syntax("a=rtcp", value)),
54        };
55        Ok(Rtcp {
56            port: grammar::port(fields[0])?,
57            address,
58        })
59    }
60}
61
62impl fmt::Display for Rtcp {
63    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64        write!(f, "{}", self.port)?;
65        if let Some(a) = &self.address {
66            write!(f, " {} {} {}", a.network_type, a.address_type, a.address)?;
67        }
68        Ok(())
69    }
70}
71
72/// `rtcp-fb-pt`: the formats an `a=rtcp-fb` line applies to.
73#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
74pub enum RtcpFbPayloadType {
75    /// `*`: every format of the media section.
76    All,
77    /// One RTP payload type.
78    PayloadType(u8),
79}
80
81impl fmt::Display for RtcpFbPayloadType {
82    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83        match self {
84            RtcpFbPayloadType::All => f.write_str("*"),
85            RtcpFbPayloadType::PayloadType(pt) => write!(f, "{pt}"),
86        }
87    }
88}
89
90/// What an `a=rtcp-fb` line stands for: the feedback messages the specifications define,
91/// and [`RtcpFbKind::Other`] for the rest.
92#[derive(Debug, Clone, PartialEq, Eq)]
93pub enum RtcpFbKind {
94    /// `ack`: positive acknowledgements (RFC 4585).
95    Ack,
96    /// `ack rpsi`: reference picture selection indication as an acknowledgement.
97    AckRpsi,
98    /// `ack app [...]`: application-defined acknowledgement.
99    AckApp,
100    /// `nack`: generic NACK (RFC 4585 section 6.2.1).
101    Nack,
102    /// `nack pli`: picture loss indication (RFC 4585 section 6.3.1).
103    NackPli,
104    /// `nack sli`: slice loss indication (RFC 4585 section 6.3.2).
105    NackSli,
106    /// `nack rpsi`: reference picture selection indication (RFC 4585 section 6.3.3).
107    NackRpsi,
108    /// `nack app [...]`: application layer feedback (RFC 4585 section 6.4).
109    NackApp,
110    /// `nack rai`: rapid acquisition (RFC 6285).
111    NackRai,
112    /// `nack tllei`: transport layer third-party loss early indication (RFC 6642).
113    NackTllei,
114    /// `nack pslei`: payload-specific third-party loss early indication (RFC 6642).
115    NackPslei,
116    /// `nack ecn`: ECN feedback (RFC 6679).
117    NackEcn,
118    /// `trr-int <ms>`: the minimum interval between regular RTCP packets (RFC 4585).
119    TrrInt(u32),
120    /// `ccm fir`: full intra request (RFC 5104 section 4.3.1).
121    CcmFir,
122    /// `ccm tmmbr [smaxpr=<n>]`: temporary maximum media bit rate request (RFC 5104
123    /// section 4.2.1), with the optional maximum packet rate.
124    CcmTmmbr {
125        /// `smaxpr`, the sender's maximum packet rate.
126        smaxpr: Option<u64>,
127    },
128    /// `ccm tstr`: temporal-spatial trade-off request (RFC 5104 section 4.3.2).
129    CcmTstr,
130    /// `ccm vbcm *(<subMessageType>)`: H.271 video back channel message (RFC 5104 section
131    /// 4.3.4).
132    CcmVbcm(Vec<u32>),
133    /// `goog-remb`: receiver estimated maximum bitrate
134    /// (draft-alvestrand-rmcat-remb).
135    GoogRemb,
136    /// `transport-cc`: transport-wide congestion control feedback
137    /// (draft-holmer-rmcat-transport-wide-cc-extensions).
138    TransportCc,
139    /// Any other feedback type: read [`RtcpFb::id`], [`RtcpFb::param`] and
140    /// [`RtcpFb::rest`].
141    Other,
142}
143
144/// `a=rtcp-fb:<pt> <id> [<param> [<rest>]]` (RFC 4585 section 4.2).
145///
146/// ```text
147/// rtcp-fb-syntax = "a=rtcp-fb:" rtcp-fb-pt SP rtcp-fb-val CRLF
148/// rtcp-fb-pt     = "*" / fmt
149/// rtcp-fb-val    = "ack" rtcp-fb-ack-param / "nack" rtcp-fb-nack-param
150///                / "trr-int" SP 1*DIGIT / rtcp-fb-id rtcp-fb-param
151/// rtcp-fb-id     = 1*(alpha-numeric / "-" / "_")
152/// rtcp-fb-param  = SP "app" [SP byte-string] / SP token [SP byte-string] / ; empty
153/// ```
154///
155/// RFC 5104 section 7.1 adds `ccm`, whose parameter is required. Every feedback type has
156/// this shape, so the line is kept as its three parts and [`RtcpFb::kind`] names the ones
157/// the specifications define.
158#[derive(Debug, Clone, PartialEq, Eq)]
159pub struct RtcpFb {
160    /// The formats the line applies to.
161    pub payload_type: RtcpFbPayloadType,
162    /// The feedback type: `ack`, `nack`, `trr-int`, `ccm`, `goog-remb`, `transport-cc`, ...
163    pub id: String,
164    /// The first parameter, a token: `pli`, `fir`, `app`, ... For `trr-int`, the interval.
165    pub param: Option<String>,
166    /// What follows the first parameter.
167    pub rest: Option<String>,
168}
169
170impl RtcpFb {
171    /// The feedback type and its parameters as one string, as it follows the payload type:
172    /// `nack pli`, `goog-remb`, `ccm fir`.
173    pub fn feedback(&self) -> String {
174        let mut out = self.id.clone();
175        for part in [&self.param, &self.rest].into_iter().flatten() {
176            out.push(' ');
177            out.push_str(part);
178        }
179        out
180    }
181
182    /// Whether the line applies to payload type `pt`.
183    pub fn applies_to(&self, pt: u8) -> bool {
184        match self.payload_type {
185            RtcpFbPayloadType::All => true,
186            RtcpFbPayloadType::PayloadType(own) => own == pt,
187        }
188    }
189
190    /// Which feedback message this is.
191    pub fn kind(&self) -> RtcpFbKind {
192        let (param, rest) = (self.param.as_deref(), self.rest.as_deref());
193        match (self.id.as_str(), param, rest) {
194            ("ack", None, _) => RtcpFbKind::Ack,
195            ("ack", Some("rpsi"), None) => RtcpFbKind::AckRpsi,
196            ("ack", Some("app"), _) => RtcpFbKind::AckApp,
197            ("nack", None, _) => RtcpFbKind::Nack,
198            ("nack", Some("pli"), None) => RtcpFbKind::NackPli,
199            ("nack", Some("sli"), None) => RtcpFbKind::NackSli,
200            ("nack", Some("rpsi"), None) => RtcpFbKind::NackRpsi,
201            ("nack", Some("app"), _) => RtcpFbKind::NackApp,
202            ("nack", Some("rai"), None) => RtcpFbKind::NackRai,
203            ("nack", Some("tllei"), None) => RtcpFbKind::NackTllei,
204            ("nack", Some("pslei"), None) => RtcpFbKind::NackPslei,
205            ("nack", Some("ecn"), None) => RtcpFbKind::NackEcn,
206            ("trr-int", Some(interval), None) => interval
207                .parse()
208                .map(RtcpFbKind::TrrInt)
209                .unwrap_or(RtcpFbKind::Other),
210            ("ccm", Some("fir"), None) => RtcpFbKind::CcmFir,
211            ("ccm", Some("tstr"), None) => RtcpFbKind::CcmTstr,
212            ("ccm", Some("tmmbr"), None) => RtcpFbKind::CcmTmmbr { smaxpr: None },
213            ("ccm", Some("tmmbr"), Some(rest)) => match rest
214                .strip_prefix("smaxpr=")
215                .filter(|n| grammar::is_digits(n) && n.len() <= 15)
216                .and_then(|n| n.parse().ok())
217            {
218                Some(smaxpr) => RtcpFbKind::CcmTmmbr {
219                    smaxpr: Some(smaxpr),
220                },
221                None => RtcpFbKind::Other,
222            },
223            ("ccm", Some("vbcm"), rest) => {
224                let types: Option<Vec<u32>> = rest
225                    .map(|r| {
226                        r.split(' ')
227                            .map(|t| {
228                                (grammar::is_digits(t) && t.len() <= 8)
229                                    .then(|| t.parse().ok())
230                                    .flatten()
231                            })
232                            .collect()
233                    })
234                    .unwrap_or_else(|| Some(vec![]));
235                types.map(RtcpFbKind::CcmVbcm).unwrap_or(RtcpFbKind::Other)
236            }
237            ("goog-remb", None, None) => RtcpFbKind::GoogRemb,
238            ("transport-cc", None, None) => RtcpFbKind::TransportCc,
239            _ => RtcpFbKind::Other,
240        }
241    }
242}
243
244impl TypedAttribute for RtcpFb {
245    const NAME: &'static str = "rtcp-fb";
246
247    fn parse(value: &str) -> Result<Self> {
248        let mut parts = value.splitn(4, ' ');
249        let (Some(pt), Some(id)) = (parts.next(), parts.next()) else {
250            return Err(syntax("a=rtcp-fb", value));
251        };
252        let (param, rest) = (parts.next(), parts.next());
253
254        let payload_type = if pt == "*" {
255            RtcpFbPayloadType::All
256        } else {
257            let pt: u8 = grammar::digits_no_leading_zero("a=rtcp-fb payload type", pt)?;
258            if pt > 127 {
259                return Err(invalid("a=rtcp-fb payload type", value));
260            }
261            RtcpFbPayloadType::PayloadType(pt)
262        };
263
264        let well_formed = grammar::is_alnum_dash_underscore(id)
265            && param.is_none_or(grammar::is_token)
266            && rest.is_none_or(grammar::is_byte_string)
267            && match id {
268                // "trr-int" SP 1*DIGIT
269                "trr-int" => param.is_some_and(grammar::is_digits) && rest.is_none(),
270                // RFC 5104: every alternative of rtcp-fb-ccm-param starts with SP.
271                "ccm" => param.is_some(),
272                _ => true,
273            };
274        if !well_formed {
275            return Err(syntax("a=rtcp-fb", value));
276        }
277
278        Ok(RtcpFb {
279            payload_type,
280            id: id.to_owned(),
281            param: param.map(str::to_owned),
282            rest: rest.map(str::to_owned),
283        })
284    }
285}
286
287impl fmt::Display for RtcpFb {
288    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
289        write!(f, "{} {}", self.payload_type, self.feedback())
290    }
291}
292
293/// `rcvr-rtt-mode`.
294#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
295pub enum RtcpXrRttMode {
296    /// `all`: every receiver may send receiver reference time reports.
297    All,
298    /// `sender`: only media senders may.
299    Sender,
300}
301
302/// `stat-flag`: a statistic of the `stat-summary` report block.
303#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
304pub enum RtcpXrStatFlag {
305    /// `loss`
306    Loss,
307    /// `dup`
308    Dup,
309    /// `jitt`
310    Jitt,
311    /// `TTL`
312    Ttl,
313    /// `HL`
314    Hl,
315}
316
317impl RtcpXrStatFlag {
318    fn as_str(self) -> &'static str {
319        match self {
320            RtcpXrStatFlag::Loss => "loss",
321            RtcpXrStatFlag::Dup => "dup",
322            RtcpXrStatFlag::Jitt => "jitt",
323            RtcpXrStatFlag::Ttl => "TTL",
324            RtcpXrStatFlag::Hl => "HL",
325        }
326    }
327}
328
329/// One `xr-format` of an `a=rtcp-xr` line.
330#[derive(Debug, Clone, PartialEq, Eq)]
331pub enum RtcpXrFormat {
332    /// `pkt-loss-rle[=<max-size>]`
333    PktLossRle(Option<u32>),
334    /// `pkt-dup-rle[=<max-size>]`
335    PktDupRle(Option<u32>),
336    /// `pkt-rcpt-times[=<max-size>]`
337    PktRcptTimes(Option<u32>),
338    /// `rcvr-rtt=<mode>[:<max-size>]`
339    RcvrRtt {
340        /// Who may send receiver reference time reports.
341        mode: RtcpXrRttMode,
342        /// The largest report block, in octets.
343        max_size: Option<u32>,
344    },
345    /// `stat-summary[=<flag>,...]`
346    StatSummary(Vec<RtcpXrStatFlag>),
347    /// `voip-metrics`
348    VoipMetrics,
349    /// `format-ext`: a report block this crate does not know, as written.
350    Other(String),
351}
352
353/// `a=rtcp-xr:[<xr-format> *(SP <xr-format>)]` (RFC 3611 section 5.1). An empty list turns
354/// extended reports off.
355#[derive(Debug, Clone, PartialEq, Eq, Default)]
356pub struct RtcpXr {
357    /// The report blocks, in order.
358    pub formats: Vec<RtcpXrFormat>,
359}
360
361fn max_size(value: &str, size: Option<&str>) -> Result<Option<u32>> {
362    size.map(|s| grammar::digits("a=rtcp-xr max-size", s).map_err(|_| syntax("a=rtcp-xr", value)))
363        .transpose()
364}
365
366impl TypedAttribute for RtcpXr {
367    const NAME: &'static str = "rtcp-xr";
368
369    fn parse(value: &str) -> Result<Self> {
370        if value.is_empty() {
371            return Ok(RtcpXr::default());
372        }
373        let mut formats = Vec::new();
374        for format in grammar::fields("a=rtcp-xr", value)? {
375            let (name, argument) = match format.split_once('=') {
376                Some((name, argument)) => (name, Some(argument)),
377                None => (format, None),
378            };
379            formats.push(match (name, argument) {
380                ("pkt-loss-rle", size) => RtcpXrFormat::PktLossRle(max_size(value, size)?),
381                ("pkt-dup-rle", size) => RtcpXrFormat::PktDupRle(max_size(value, size)?),
382                ("pkt-rcpt-times", size) => RtcpXrFormat::PktRcptTimes(max_size(value, size)?),
383                ("rcvr-rtt", Some(argument)) => {
384                    let (mode, size) = match argument.split_once(':') {
385                        Some((mode, size)) => (mode, Some(size)),
386                        None => (argument, None),
387                    };
388                    RtcpXrFormat::RcvrRtt {
389                        mode: match mode {
390                            "all" => RtcpXrRttMode::All,
391                            "sender" => RtcpXrRttMode::Sender,
392                            _ => return Err(syntax("a=rtcp-xr rcvr-rtt", value)),
393                        },
394                        max_size: max_size(value, size)?,
395                    }
396                }
397                ("rcvr-rtt", None) => return Err(syntax("a=rtcp-xr rcvr-rtt", value)),
398                ("stat-summary", flags) => RtcpXrFormat::StatSummary(
399                    flags
400                        .map(|flags| {
401                            flags
402                                .split(',')
403                                .map(|flag| match flag {
404                                    "loss" => Ok(RtcpXrStatFlag::Loss),
405                                    "dup" => Ok(RtcpXrStatFlag::Dup),
406                                    "jitt" => Ok(RtcpXrStatFlag::Jitt),
407                                    "TTL" => Ok(RtcpXrStatFlag::Ttl),
408                                    "HL" => Ok(RtcpXrStatFlag::Hl),
409                                    _ => Err(syntax("a=rtcp-xr stat-summary", value)),
410                                })
411                                .collect::<Result<Vec<_>>>()
412                        })
413                        .transpose()?
414                        .unwrap_or_default(),
415                ),
416                ("voip-metrics", None) => RtcpXrFormat::VoipMetrics,
417                // format-ext = non-ws-string
418                _ if grammar::is_non_ws_string(format) => RtcpXrFormat::Other(format.to_owned()),
419                _ => return Err(syntax("a=rtcp-xr", value)),
420            });
421        }
422        Ok(RtcpXr { formats })
423    }
424}
425
426impl fmt::Display for RtcpXr {
427    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
428        let size = |f: &mut fmt::Formatter<'_>, name: &str, size: &Option<u32>| match size {
429            Some(size) => write!(f, "{name}={size}"),
430            None => f.write_str(name),
431        };
432        for (i, format) in self.formats.iter().enumerate() {
433            if i > 0 {
434                f.write_str(" ")?;
435            }
436            match format {
437                RtcpXrFormat::PktLossRle(s) => size(f, "pkt-loss-rle", s)?,
438                RtcpXrFormat::PktDupRle(s) => size(f, "pkt-dup-rle", s)?,
439                RtcpXrFormat::PktRcptTimes(s) => size(f, "pkt-rcpt-times", s)?,
440                RtcpXrFormat::RcvrRtt { mode, max_size } => {
441                    f.write_str(match mode {
442                        RtcpXrRttMode::All => "rcvr-rtt=all",
443                        RtcpXrRttMode::Sender => "rcvr-rtt=sender",
444                    })?;
445                    if let Some(max_size) = max_size {
446                        write!(f, ":{max_size}")?;
447                    }
448                }
449                RtcpXrFormat::StatSummary(flags) => {
450                    f.write_str("stat-summary")?;
451                    for (j, flag) in flags.iter().enumerate() {
452                        f.write_str(if j == 0 { "=" } else { "," })?;
453                        f.write_str(flag.as_str())?;
454                    }
455                }
456                RtcpXrFormat::VoipMetrics => f.write_str("voip-metrics")?,
457                RtcpXrFormat::Other(other) => f.write_str(other)?,
458            }
459        }
460        Ok(())
461    }
462}