broadcast-common 15.0.0

Foundation for the rust-broadcast crates: CRC-32/MPEG-2, BCD + MJD time codecs, hex and base64 codecs, 33-bit/PCR clock arithmetic, wrap-safe modular counters, SDP media sections and the bounded XML reader. no_std + alloc.
Documentation
//! The media-section model of a Session Description Protocol document
//! (RFC 4566 §5.14, §5.13): the `m=` line's media type, port, transport protocol and format
//! list, and the `a=` attributes under it in wire order.
//!
//! It is the vocabulary the RTP crates exchange: `transmux` builds a section from a track and
//! reads one back as a playable track, `rtsp-runtime` writes and parses whole session
//! descriptions over it, and no SDP library's type crosses a crate boundary. Nothing here
//! parses or renders text.
//!
//! [`SdpMedia`] is a deliberately lossy view of a section: the `m=` line's media type, port,
//! protocol and format list (its port count, as in `m=video 5000/2`, is not kept) and the `a=`
//! attributes; a section's `i=`, `c=`, `b=` and `k=` lines have no field here and are dropped
//! by any parser that fills it.

use alloc::string::{String, ToString};
use alloc::vec::Vec;

/// The `<media>` token of an `m=` line (RFC 4566 §5.14).
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum SdpMediaType {
    /// `video`
    Video,
    /// `audio`
    Audio,
    /// `text`
    Text,
    /// `application`
    Application,
    /// `message`
    Message,
    /// A media token outside the RFC 4566 §8.2.1 registry. It cannot hold a registered token or
    /// an invalid one: build the type through [`SdpMediaType::parse`].
    Other(OtherMediaType),
}

/// A media token that is a valid RFC 4566 `token` but not in the §8.2.1 registry; built only by
/// [`SdpMediaType::parse`], so `Other` never holds `video`, `audio`, `text`, `application` or
/// `message`, and a value that renders always parses back to itself.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct OtherMediaType(String);

impl OtherMediaType {
    /// The token as written on the `m=` line.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

/// A text that is not an RFC 4566 §9 `token`: empty, or holding a character outside the
/// `token-char` set (a space or a control character would split the line).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InvalidSdpToken;

impl core::fmt::Display for InvalidSdpToken {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_str("not an RFC 4566 token")
    }
}

impl core::error::Error for InvalidSdpToken {}

const fn is_token_char(byte: u8) -> bool {
    matches!(byte, 0x21 | 0x23..=0x27 | 0x2A | 0x2B | 0x2D | 0x2E | 0x30..=0x39 | 0x41..=0x5A | 0x5E..=0x7E)
}

impl SdpMediaType {
    /// The token as written on the `m=` line.
    #[must_use]
    pub fn as_str(&self) -> &str {
        match self {
            Self::Video => "video",
            Self::Audio => "audio",
            Self::Text => "text",
            Self::Application => "application",
            Self::Message => "message",
            Self::Other(token) => token.as_str(),
        }
    }

    /// The registered token, or `"other"` for one outside the registry.
    #[must_use]
    pub fn name(&self) -> &'static str {
        match self {
            Self::Video => "video",
            Self::Audio => "audio",
            Self::Text => "text",
            Self::Application => "application",
            Self::Message => "message",
            Self::Other(_) => "other",
        }
    }
}

impl SdpMediaType {
    /// The media type of `token`: a registered token is its variant, any other RFC 4566 `token` is
    /// [`SdpMediaType::Other`].
    ///
    /// # Errors
    ///
    /// [`InvalidSdpToken`] when `token` is empty or holds a character outside `token-char`.
    pub fn parse(token: &str) -> Result<Self, InvalidSdpToken> {
        if token.is_empty() || !token.bytes().all(is_token_char) {
            return Err(InvalidSdpToken);
        }
        Ok(match token {
            "video" => Self::Video,
            "audio" => Self::Audio,
            "text" => Self::Text,
            "application" => Self::Application,
            "message" => Self::Message,
            other => Self::Other(OtherMediaType(other.to_string())),
        })
    }
}

impl core::fmt::Display for SdpMediaType {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// One `a=` attribute (RFC 4566 §5.13): a property (`a=recvonly`) or `name:value`.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct SdpAttribute {
    /// The attribute name.
    pub name: String,
    /// The value after the `:`, or `None` for a property attribute.
    pub value: Option<String>,
}

impl SdpAttribute {
    /// An `a=name:value` attribute.
    #[must_use]
    pub fn with_value(name: impl Into<String>, value: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            value: Some(value.into()),
        }
    }

    /// An `a=name` property attribute.
    #[must_use]
    pub fn property(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            value: None,
        }
    }
}

/// One media description: an `m=` line and the attributes under it (RFC 4566 §5.14).
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct SdpMedia {
    /// The media type.
    pub media_type: SdpMediaType,
    /// The transport port, `0` when the section is a description only.
    pub port: u16,
    /// The transport protocol token (`RTP/AVP`).
    pub protocol: String,
    /// The `fmt` list: for RTP the payload types, space separated.
    pub formats: String,
    /// The `a=` attributes in wire order.
    pub attributes: Vec<SdpAttribute>,
}

/// The transport protocol token of an RTP section over RTP/AVP (RFC 3551 §6).
pub const RTP_AVP: &str = "RTP/AVP";

impl SdpMedia {
    /// A section of `media_type` on port `0`, over RTP/AVP, listing `formats`, with no attributes.
    #[must_use]
    pub fn rtp_avp(media_type: SdpMediaType, formats: impl Into<String>) -> Self {
        Self {
            media_type,
            port: 0,
            protocol: RTP_AVP.to_string(),
            formats: formats.into(),
            attributes: Vec::new(),
        }
    }

    /// Appends an `a=name:value` attribute.
    pub fn add_attribute_with_value(&mut self, name: impl Into<String>, value: impl Into<String>) {
        self.attributes.push(SdpAttribute::with_value(name, value));
    }

    /// The first attribute called `name`: `Some(None)` for a property, `Some(Some(value))` for
    /// a valued one, `None` when absent.
    #[must_use]
    pub fn get_first_attribute_value(&self, name: &str) -> Option<Option<&str>> {
        self.attributes
            .iter()
            .find(|attribute| attribute.name == name)
            .map(|attribute| attribute.value.as_deref())
    }

    /// Every value of the attributes called `name`, in wire order.
    pub fn attribute_values<'a, 'n>(
        &'a self,
        name: &'n str,
    ) -> impl Iterator<Item = &'a str> + use<'a, 'n> {
        self.attributes
            .iter()
            .filter(move |attribute| attribute.name == name)
            .filter_map(|attribute| attribute.value.as_deref())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn media_type_tokens_round_trip() {
        for token in [
            "video",
            "audio",
            "text",
            "application",
            "message",
            "control",
        ] {
            let media_type = SdpMediaType::parse(token).expect("a token");
            assert_eq!(media_type.as_str(), token);
            assert_eq!(SdpMediaType::parse(media_type.as_str()), Ok(media_type));
        }
        assert_eq!(
            SdpMediaType::parse("control").expect("a token").name(),
            "other"
        );
    }

    #[test]
    fn a_registered_token_has_one_value_and_a_non_token_is_refused() {
        assert_eq!(SdpMediaType::parse("video"), Ok(SdpMediaType::Video));
        for bad in ["", "vid eo", "video\r\nm=audio", "a=b", "x\u{e9}"] {
            assert_eq!(SdpMediaType::parse(bad), Err(InvalidSdpToken), "{bad:?}");
        }
    }

    #[test]
    fn attribute_lookup_keeps_wire_order() {
        let mut media = SdpMedia::rtp_avp(SdpMediaType::Video, "96");
        media.add_attribute_with_value("rtpmap", "96 H264/90000");
        media.attributes.push(SdpAttribute::property("recvonly"));
        media.add_attribute_with_value("fmtp", "96 a=b");
        media.add_attribute_with_value("fmtp", "96 c=d");
        assert_eq!(
            media.get_first_attribute_value("rtpmap"),
            Some(Some("96 H264/90000"))
        );
        assert_eq!(media.get_first_attribute_value("recvonly"), Some(None));
        assert_eq!(media.get_first_attribute_value("control"), None);
        assert_eq!(
            media.attribute_values("fmtp").collect::<Vec<_>>(),
            ["96 a=b", "96 c=d"]
        );
    }
}