Skip to main content

rtci_sdp/attribute/
rtp.rs

1//! `a=rtpmap`, `a=fmtp`, `a=ptime`, `a=maxptime`, `a=framerate` (RFC 8866 section 6),
2//! `a=imageattr` (RFC 6236) and `a=content` (RFC 4796).
3
4use std::fmt;
5
6use shared::error::Result;
7
8use super::TypedAttribute;
9use crate::grammar::{self, invalid, syntax};
10
11/// An RTP payload type: `zero-based-integer`, 0 to 127.
12pub(crate) fn payload_type(what: &str, value: &str) -> Result<u8> {
13    let pt: u8 = grammar::digits_no_leading_zero(what, value)?;
14    if pt > 127 {
15        return Err(invalid(what, value));
16    }
17    Ok(pt)
18}
19
20/// `a=rtpmap:<payload type> <encoding name>/<clock rate>[/<encoding params>]` (RFC 8866
21/// section 6.6).
22///
23/// ```text
24/// rtpmap-value    = payload-type SP encoding-name "/" clock-rate [ "/" encoding-params ]
25/// payload-type    = zero-based-integer
26/// encoding-name   = token
27/// clock-rate      = integer
28/// encoding-params = channels
29/// channels        = integer
30/// ```
31#[derive(Debug, Clone, PartialEq, Eq, Hash)]
32pub struct RtpMap {
33    /// The payload type, 0 to 127.
34    pub payload_type: u8,
35    /// The encoding name, as written. Names are compared without regard to case
36    /// (section 6.6): see [`RtpMap::is_encoding`].
37    pub encoding_name: String,
38    /// The RTP clock rate, in Hz. Never zero.
39    pub clock_rate: u32,
40    /// The number of audio channels, when the line gives it. Section 6.6: it "MAY be
41    /// omitted if the number of channels is one".
42    pub channels: Option<u32>,
43}
44
45impl RtpMap {
46    /// Whether the encoding is `name`, compared as media subtypes are: without regard to
47    /// case.
48    pub fn is_encoding(&self, name: &str) -> bool {
49        self.encoding_name.eq_ignore_ascii_case(name)
50    }
51}
52
53impl TypedAttribute for RtpMap {
54    const NAME: &'static str = "rtpmap";
55
56    fn parse(value: &str) -> Result<Self> {
57        let Some((pt, encoding)) = value.split_once(' ') else {
58            return Err(syntax("a=rtpmap", value));
59        };
60        let mut parts = encoding.split('/');
61        let (Some(name), Some(clock_rate)) = (parts.next(), parts.next()) else {
62            return Err(syntax("a=rtpmap", value));
63        };
64        let channels = parts.next();
65        let integer = |what: &str, v: &str| -> Result<u32> {
66            if !grammar::is_integer(v) {
67                return Err(syntax(what, value));
68            }
69            v.parse().map_err(|_| invalid(what, value))
70        };
71        if parts.next().is_some() || !grammar::is_token(name) {
72            return Err(syntax("a=rtpmap", value));
73        }
74        Ok(RtpMap {
75            payload_type: payload_type("a=rtpmap payload type", pt)?,
76            encoding_name: name.to_owned(),
77            clock_rate: integer("a=rtpmap clock rate", clock_rate)?,
78            channels: channels
79                .map(|c| integer("a=rtpmap channels", c))
80                .transpose()?,
81        })
82    }
83}
84
85impl fmt::Display for RtpMap {
86    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
87        write!(
88            f,
89            "{} {}/{}",
90            self.payload_type, self.encoding_name, self.clock_rate
91        )?;
92        if let Some(channels) = self.channels {
93            write!(f, "/{channels}")?;
94        }
95        Ok(())
96    }
97}
98
99/// `a=fmtp:<format> <format specific parameters>` (RFC 8866 section 6.15).
100///
101/// The parameters are a byte-string that SDP conveys "unchanged" to the format: everything
102/// after the first space, spaces included. [`Fmtp::parameter_list`] reads the
103/// `name=value;name=value` shape most RTP payload formats use (RFC 4855), without changing
104/// the text or the order.
105#[derive(Debug, Clone, PartialEq, Eq, Hash)]
106pub struct Fmtp {
107    /// The format: for RTP, a payload type.
108    pub format: String,
109    /// The format-specific parameters, exactly as written.
110    pub parameters: String,
111}
112
113impl Fmtp {
114    /// The format as an RTP payload type, when it is one.
115    pub fn payload_type(&self) -> Option<u8> {
116        payload_type("fmt", &self.format).ok()
117    }
118
119    /// The parameters split at `;`, each into its name and (after the first `=`) its
120    /// value, with the white space around them removed, in the order written.
121    ///
122    /// A part without `=` has no value: `a=fmtp:101 0-16` (RFC 4733 events) is one such
123    /// part. Empty parts (a trailing `;`) are skipped.
124    pub fn parameter_list(&self) -> Vec<(&str, Option<&str>)> {
125        self.parameters
126            .split(';')
127            .map(str::trim)
128            .filter(|part| !part.is_empty())
129            .map(|part| match part.split_once('=') {
130                Some((name, value)) => (name.trim_end(), Some(value.trim_start())),
131                None => (part, None),
132            })
133            .collect()
134    }
135
136    /// The value of the parameter `name`, compared without regard to case (RFC 4855
137    /// section 3: parameter names are case-insensitive). The first one wins.
138    pub fn parameter(&self, name: &str) -> Option<&str> {
139        self.parameter_list()
140            .into_iter()
141            .find(|(n, _)| n.eq_ignore_ascii_case(name))
142            .and_then(|(_, value)| value)
143    }
144}
145
146impl TypedAttribute for Fmtp {
147    const NAME: &'static str = "fmtp";
148
149    fn parse(value: &str) -> Result<Self> {
150        match value.split_once(' ') {
151            Some((format, parameters))
152                if grammar::is_token(format) && grammar::is_byte_string(parameters) =>
153            {
154                Ok(Fmtp {
155                    format: format.to_owned(),
156                    parameters: parameters.to_owned(),
157                })
158            }
159            _ => Err(syntax("a=fmtp", value)),
160        }
161    }
162}
163
164impl fmt::Display for Fmtp {
165    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
166        write!(f, "{} {}", self.format, self.parameters)
167    }
168}
169
170/// A value attribute whose value is a `non-zero-int-or-real`.
171macro_rules! real_attribute {
172    ($(#[$doc:meta])* $name:ident, $key:literal) => {
173        $(#[$doc])*
174        #[derive(Debug, Clone, PartialEq, Eq, Hash)]
175        pub struct $name(String);
176
177        impl $name {
178            /// The value as written: an integer, or a real without a trailing zero.
179            pub fn as_str(&self) -> &str {
180                &self.0
181            }
182
183            /// The value as a number. It is never zero.
184            pub fn value(&self) -> f64 {
185                // Checked by `parse`: digits with at most one point.
186                self.0.parse().unwrap_or(f64::NAN)
187            }
188        }
189
190        impl TypedAttribute for $name {
191            const NAME: &'static str = $key;
192
193            fn parse(value: &str) -> Result<Self> {
194                if grammar::is_non_zero_int_or_real(value) {
195                    Ok($name(value.to_owned()))
196                } else {
197                    Err(syntax(concat!("a=", $key), value))
198                }
199            }
200        }
201
202        impl fmt::Display for $name {
203            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
204                f.write_str(&self.0)
205            }
206        }
207    };
208}
209
210real_attribute!(
211    /// `a=ptime:<packet time>` (RFC 8866 section 6.4): the length of media in a packet the
212    /// receiver prefers, in milliseconds.
213    Ptime,
214    "ptime"
215);
216real_attribute!(
217    /// `a=maxptime:<maximum packet time>` (RFC 8866 section 6.5): the most media a packet
218    /// may carry, in milliseconds.
219    MaxPtime,
220    "maxptime"
221);
222real_attribute!(
223    /// `a=framerate:<frame rate>` (RFC 8866 section 6.13): the maximum video frame rate, in
224    /// frames per second.
225    FrameRate,
226    "framerate"
227);
228
229/// `a=content:<tag>[,<tag>...]` (RFC 4796 section 5): what a media stream shows.
230///
231/// The tags RFC 4796 defines are `slides`, `speaker`, `sl`, `main` and `alt`; any token is
232/// accepted, and one that is not known is to be ignored (section 5).
233#[derive(Debug, Clone, PartialEq, Eq)]
234pub struct Content {
235    /// The tags, in order. Never empty.
236    pub tags: Vec<String>,
237}
238
239impl TypedAttribute for Content {
240    const NAME: &'static str = "content";
241
242    fn parse(value: &str) -> Result<Self> {
243        let tags: Vec<String> = value.split(',').map(str::to_owned).collect();
244        if !tags.iter().all(|tag| grammar::is_token(tag)) {
245            return Err(syntax("a=content", value));
246        }
247        Ok(Content { tags })
248    }
249}
250
251impl fmt::Display for Content {
252    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
253        f.write_str(&self.tags.join(","))
254    }
255}
256
257/// A range of an `a=imageattr` set: `xyrange` for `x=` and `y=`, `srange` for `sar=`.
258#[derive(Debug, Clone, PartialEq)]
259pub enum ImageAttrRange<T> {
260    /// One value.
261    Value(T),
262    /// `[min:max]` or `[min:step:max]` for pixels, `[min-max]` for an aspect ratio.
263    Range {
264        /// The lower bound.
265        min: T,
266        /// The step between values, for pixel ranges that give one.
267        step: Option<T>,
268        /// The upper bound.
269        max: T,
270    },
271    /// `[a,b,...]`: any of the listed values, at least two.
272    List(Vec<T>),
273}
274
275/// One `[x=...,y=...,...]` set of an `a=imageattr` line.
276#[derive(Debug, Clone, PartialEq)]
277pub struct ImageAttrSet {
278    /// `x=`: the image width, in pixels.
279    pub x: ImageAttrRange<u32>,
280    /// `y=`: the image height, in pixels.
281    pub y: ImageAttrRange<u32>,
282    /// `sar=`: the sample (pixel) aspect ratio.
283    pub sar: Option<ImageAttrRange<f64>>,
284    /// `par=[min-max]`: the picture aspect ratio.
285    pub par: Option<(f64, f64)>,
286    /// `q=`: the preference for this set, 0.0 to 1.0; 0.5 when absent.
287    pub q: Option<f64>,
288}
289
290/// The attribute list of one direction of an `a=imageattr` line.
291#[derive(Debug, Clone, PartialEq)]
292pub enum ImageAttrList {
293    /// `*`: no restriction is stated.
294    Any,
295    /// One or more sets.
296    Sets(Vec<ImageAttrSet>),
297}
298
299/// `a=imageattr:<pt> (send|recv) <attr-list> [(send|recv) <attr-list>]` (RFC 6236 section
300/// 3.1).
301///
302/// ```text
303/// image-attr = "imageattr:" PT 1*2( 1*WSP ( "send" / "recv" ) 1*WSP attr-list )
304/// PT         = 1*DIGIT / "*"
305/// attr-list  = ( set *(1*WSP set) ) / "*"
306/// set        = "[" "x=" xyrange "," "y=" xyrange *( "," key-value ) "]"
307/// key-value  = ( "sar=" srange ) / ( "par=" prange ) / ( "q=" qvalue )
308/// xyrange    = ( "[" xyvalue ":" [ step ":" ] xyvalue "]" )
309///            / ( "[" xyvalue 1*( "," xyvalue ) "]" ) / ( xyvalue )
310/// srange     = ( "[" spvalue 1*( "," spvalue ) "]" ) / ( "[" spvalue "-" spvalue "]" )
311///            / ( spvalue )
312/// prange     = ( "[" spvalue "-" spvalue "]" )
313/// ```
314#[derive(Debug, Clone, PartialEq)]
315pub struct ImageAttr {
316    /// The payload type; `None` for `*`, every payload type of the section.
317    pub payload_type: Option<u8>,
318    /// What the endpoint sends.
319    pub send: Option<ImageAttrList>,
320    /// What the endpoint receives.
321    pub recv: Option<ImageAttrList>,
322    /// Whether `recv` was written before `send`. Both orders mean the same.
323    pub recv_first: bool,
324}
325
326/// `xyvalue = onetonine *5DIGIT`.
327fn xyvalue(value: &str, v: &str) -> Result<u32> {
328    if !grammar::is_integer(v) || v.len() > 6 {
329        return Err(syntax("a=imageattr x/y value", value));
330    }
331    v.parse().map_err(|_| syntax("a=imageattr", value))
332}
333
334/// `spvalue = ( "0" "." onetonine *3DIGIT ) / ( onetonine "." 1*4DIGIT )`.
335fn spvalue(value: &str, v: &str) -> Result<f64> {
336    let b = v.as_bytes();
337    let ok = b.len() >= 3
338        && b.len() <= 6
339        && b[1] == b'.'
340        && b[2..].iter().all(u8::is_ascii_digit)
341        && match b[0] {
342            b'0' => b[2] != b'0',
343            b'1'..=b'9' => true,
344            _ => false,
345        };
346    if !ok {
347        return Err(syntax("a=imageattr aspect ratio", value));
348    }
349    v.parse().map_err(|_| syntax("a=imageattr", value))
350}
351
352/// `qvalue = ( "0" "." 1*2DIGIT ) / ( "1" "." 1*2("0") )`.
353fn qvalue(value: &str, v: &str) -> Result<f64> {
354    let b = v.as_bytes();
355    let ok = (3..=4).contains(&b.len())
356        && b[1] == b'.'
357        && match b[0] {
358            b'0' => b[2..].iter().all(u8::is_ascii_digit),
359            b'1' => b[2..].iter().all(|d| *d == b'0'),
360            _ => false,
361        };
362    if !ok {
363        return Err(syntax("a=imageattr q", value));
364    }
365    v.parse().map_err(|_| syntax("a=imageattr", value))
366}
367
368fn xyrange(value: &str, v: &str) -> Result<ImageAttrRange<u32>> {
369    let Some(inner) = v.strip_prefix('[') else {
370        return xyvalue(value, v).map(ImageAttrRange::Value);
371    };
372    let inner = inner
373        .strip_suffix(']')
374        .ok_or_else(|| syntax("a=imageattr", value))?;
375    if inner.contains(':') {
376        let parts: Vec<&str> = inner.split(':').collect();
377        let (min, step, max) = match parts[..] {
378            [min, max] => (min, None, max),
379            [min, step, max] => (min, Some(step), max),
380            _ => return Err(syntax("a=imageattr range", value)),
381        };
382        return Ok(ImageAttrRange::Range {
383            min: xyvalue(value, min)?,
384            step: step.map(|s| xyvalue(value, s)).transpose()?,
385            max: xyvalue(value, max)?,
386        });
387    }
388    let list = inner
389        .split(',')
390        .map(|x| xyvalue(value, x))
391        .collect::<Result<Vec<_>>>()?;
392    if list.len() < 2 {
393        return Err(syntax("a=imageattr list", value));
394    }
395    Ok(ImageAttrRange::List(list))
396}
397
398fn srange(value: &str, v: &str) -> Result<ImageAttrRange<f64>> {
399    let Some(inner) = v.strip_prefix('[') else {
400        return spvalue(value, v).map(ImageAttrRange::Value);
401    };
402    let inner = inner
403        .strip_suffix(']')
404        .ok_or_else(|| syntax("a=imageattr", value))?;
405    if let Some((min, max)) = inner.split_once('-') {
406        return Ok(ImageAttrRange::Range {
407            min: spvalue(value, min)?,
408            step: None,
409            max: spvalue(value, max)?,
410        });
411    }
412    let list = inner
413        .split(',')
414        .map(|x| spvalue(value, x))
415        .collect::<Result<Vec<_>>>()?;
416    if list.len() < 2 {
417        return Err(syntax("a=imageattr list", value));
418    }
419    Ok(ImageAttrRange::List(list))
420}
421
422/// Splits the inside of a set at the commas that are not inside a bracketed range.
423fn split_top_level(inner: &str) -> Vec<&str> {
424    let mut parts = Vec::new();
425    let (mut depth, mut start) = (0usize, 0usize);
426    for (i, b) in inner.bytes().enumerate() {
427        match b {
428            b'[' => depth += 1,
429            b']' => depth = depth.saturating_sub(1),
430            b',' if depth == 0 => {
431                parts.push(&inner[start..i]);
432                start = i + 1;
433            }
434            _ => {}
435        }
436    }
437    parts.push(&inner[start..]);
438    parts
439}
440
441fn image_set(value: &str, set: &str) -> Result<ImageAttrSet> {
442    let inner = set
443        .strip_prefix('[')
444        .and_then(|s| s.strip_suffix(']'))
445        .ok_or_else(|| syntax("a=imageattr set", value))?;
446    let parts = split_top_level(inner);
447    let (Some(x), Some(y)) = (
448        parts.first().and_then(|p| p.strip_prefix("x=")),
449        parts.get(1).and_then(|p| p.strip_prefix("y=")),
450    ) else {
451        return Err(syntax("a=imageattr set", value));
452    };
453    let mut out = ImageAttrSet {
454        x: xyrange(value, x)?,
455        y: xyrange(value, y)?,
456        sar: None,
457        par: None,
458        q: None,
459    };
460    for part in &parts[2..] {
461        if let Some(sar) = part.strip_prefix("sar=") {
462            out.sar = Some(srange(value, sar)?);
463        } else if let Some(par) = part.strip_prefix("par=") {
464            let (min, max) = par
465                .strip_prefix('[')
466                .and_then(|p| p.strip_suffix(']'))
467                .and_then(|p| p.split_once('-'))
468                .ok_or_else(|| syntax("a=imageattr par", value))?;
469            out.par = Some((spvalue(value, min)?, spvalue(value, max)?));
470        } else if let Some(q) = part.strip_prefix("q=") {
471            out.q = Some(qvalue(value, q)?);
472        } else {
473            return Err(syntax("a=imageattr key", value));
474        }
475    }
476    Ok(out)
477}
478
479impl TypedAttribute for ImageAttr {
480    const NAME: &'static str = "imageattr";
481
482    fn parse(value: &str) -> Result<Self> {
483        // 1*WSP separates everything, and nothing inside a set has white space.
484        let mut tokens = value
485            .split([' ', '\t'])
486            .filter(|t| !t.is_empty())
487            .peekable();
488        if value.starts_with([' ', '\t']) || value.ends_with([' ', '\t']) {
489            return Err(syntax("a=imageattr", value));
490        }
491        let pt = match tokens.next() {
492            Some("*") => None,
493            Some(pt) => Some(payload_type("a=imageattr payload type", pt)?),
494            None => return Err(syntax("a=imageattr", value)),
495        };
496
497        let mut out = ImageAttr {
498            payload_type: pt,
499            send: None,
500            recv: None,
501            recv_first: false,
502        };
503        let mut directions = 0;
504        while let Some(direction) = tokens.next() {
505            let slot = match direction {
506                "send" => &mut out.send,
507                "recv" => {
508                    out.recv_first = directions == 0;
509                    &mut out.recv
510                }
511                _ => return Err(syntax("a=imageattr direction", value)),
512            };
513            if slot.is_some() {
514                return Err(syntax("a=imageattr: a direction occurs twice", value));
515            }
516            let list = if tokens.peek() == Some(&"*") {
517                tokens.next();
518                ImageAttrList::Any
519            } else {
520                let mut sets = Vec::new();
521                while let Some(set) = tokens.next_if(|t| t.starts_with('[')) {
522                    sets.push(image_set(value, set)?);
523                }
524                if sets.is_empty() {
525                    return Err(syntax("a=imageattr attr-list", value));
526                }
527                ImageAttrList::Sets(sets)
528            };
529            *slot = Some(list);
530            directions += 1;
531        }
532        if directions == 0 {
533            return Err(syntax("a=imageattr", value));
534        }
535        Ok(out)
536    }
537}
538
539fn write_range<T: fmt::Display>(
540    f: &mut fmt::Formatter<'_>,
541    range: &ImageAttrRange<T>,
542    range_separator: char,
543) -> fmt::Result {
544    match range {
545        ImageAttrRange::Value(v) => write!(f, "{v}"),
546        ImageAttrRange::Range { min, step, max } => {
547            write!(f, "[{min}{range_separator}")?;
548            if let Some(step) = step {
549                write!(f, "{step}{range_separator}")?;
550            }
551            write!(f, "{max}]")
552        }
553        ImageAttrRange::List(list) => {
554            f.write_str("[")?;
555            for (i, v) in list.iter().enumerate() {
556                if i > 0 {
557                    f.write_str(",")?;
558                }
559                write!(f, "{v}")?;
560            }
561            f.write_str("]")
562        }
563    }
564}
565
566/// An aspect ratio or a preference with the decimal point the grammar requires.
567struct Decimal(f64);
568
569impl fmt::Display for Decimal {
570    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
571        if self.0.fract() == 0.0 {
572            write!(f, "{:.1}", self.0)
573        } else {
574            write!(f, "{}", self.0)
575        }
576    }
577}
578
579impl fmt::Display for ImageAttrSet {
580    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
581        f.write_str("[x=")?;
582        write_range(f, &self.x, ':')?;
583        f.write_str(",y=")?;
584        write_range(f, &self.y, ':')?;
585        if let Some(sar) = &self.sar {
586            f.write_str(",sar=")?;
587            let sar = match sar {
588                ImageAttrRange::Value(v) => ImageAttrRange::Value(Decimal(*v)),
589                ImageAttrRange::Range { min, max, .. } => ImageAttrRange::Range {
590                    min: Decimal(*min),
591                    step: None,
592                    max: Decimal(*max),
593                },
594                ImageAttrRange::List(list) => {
595                    ImageAttrRange::List(list.iter().map(|v| Decimal(*v)).collect())
596                }
597            };
598            write_range(f, &sar, '-')?;
599        }
600        if let Some((min, max)) = self.par {
601            write!(f, ",par=[{}-{}]", Decimal(min), Decimal(max))?;
602        }
603        if let Some(q) = self.q {
604            write!(f, ",q={}", Decimal(q))?;
605        }
606        f.write_str("]")
607    }
608}
609
610impl fmt::Display for ImageAttr {
611    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
612        match self.payload_type {
613            Some(pt) => write!(f, "{pt}")?,
614            None => f.write_str("*")?,
615        }
616        let (send, recv) = (("send", &self.send), ("recv", &self.recv));
617        let order = if self.recv_first {
618            [recv, send]
619        } else {
620            [send, recv]
621        };
622        for (direction, list) in order {
623            match list {
624                None => {}
625                Some(ImageAttrList::Any) => write!(f, " {direction} *")?,
626                Some(ImageAttrList::Sets(sets)) => {
627                    write!(f, " {direction}")?;
628                    for set in sets {
629                        write!(f, " {set}")?;
630                    }
631                }
632            }
633        }
634        Ok(())
635    }
636}