rtci 0.5.0

A sans-I/O WebRTC implementation: peer connections with ICE, DTLS-SRTP, SCTP data channels, RTP/RTCP and JSEP negotiation
Documentation
pub(crate) mod av1;
pub(crate) mod generic;
pub(crate) mod h264;
pub(crate) mod h265;
pub(crate) mod vp9;

use std::any::Any;
use std::collections::HashMap;
use std::fmt;

use av1::Av1Fmtp;
use generic::GenericFmtp;
use h264::H264Fmtp;
use h265::H265Fmtp;
use vp9::Vp9Fmtp;

/// Fmtp interface for implementing custom
/// Fmtp parsers based on mime_type
pub(crate) trait Fmtp: fmt::Debug {
    /// mime_type returns the mime_type associated with
    /// the fmtp
    fn mime_type(&self) -> &str;

    /// match_fmtp compares two fmtp descriptions for
    /// compatibility based on the mime_type    
    fn match_fmtp(&self, f: &dyn Fmtp) -> bool;

    /// parameter returns a value for the associated key
    /// if contained in the parsed fmtp string
    fn parameter(&self, key: &str) -> Option<&String>;

    fn equal(&self, other: &dyn Fmtp) -> bool;
    fn as_any(&self) -> &dyn Any;
}

impl PartialEq for dyn Fmtp {
    fn eq(&self, other: &Self) -> bool {
        self.equal(other)
    }
}

/// What a media type parameter declares, as the tables of RFC 6184 section 8.2.2 (Table 6)
/// and RFC 7798 section 7.2.2 (Table 1) classify every parameter of H.264 and H.265.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ParameterRole {
    /// C (and H.265's D): the media format configuration, for sending and receiving. It
    /// decides whether two formats are one ([`Fmtp::match_fmtp`]); an answer keeps it, the
    /// level aside, or removes the format.
    Configuration,
    /// R: what the declaring side can receive. The peer's are the limits this endpoint sends
    /// under (`RTCRtpSender::send_restrictions`); this endpoint's are its own, never the
    /// peer's echoed.
    ReceiverCapability,
    /// P: a property of the stream the declaring side sends (decoding order, buffering,
    /// segmentation). The peer's configure the depacketizer (`RTCRtpCodec::h264_depacketizer`,
    /// `h265_depacketizer`).
    StreamProperty,
    /// S (and H.265's `sprop-vps` / `-sps` / `-pps`): out-of-band parameter sets of the
    /// stream the declaring side sends (`RTCRtpCodec::sprop_parameter_sets`).
    ParameterSets,
    /// O: offer/answer mode, H.264's `level-asymmetry-allowed`: which level each direction
    /// uses (the H.264 answer's level).
    OfferAnswer,
    /// O / X: H.265's `recv-sub-layer-id`, the operation point an answer selects; never in an
    /// offer.
    OperationPoint,
}

/// One row of RFC 6184 Table 6 or RFC 7798 Table 1: a parameter, its role, and whether it is
/// usable in a `recvonly` and in a `sendonly` description (`-` in the table: "not usable";
/// every parameter is usable in `sendrecv`).
pub(crate) struct ParameterUse {
    pub(crate) name: &'static str,
    pub(crate) role: ParameterRole,
    pub(crate) recvonly: bool,
    pub(crate) sendonly: bool,
}

/// The parameter table of a media type: H.264's and H.265's; `None` for another.
pub(crate) fn parameter_table(mime_type: &str) -> Option<&'static [ParameterUse]> {
    if mime_type.eq_ignore_ascii_case("video/h264") {
        Some(h264::PARAMETERS)
    } else if mime_type.eq_ignore_ascii_case("video/h265") {
        Some(h265::PARAMETERS)
    } else {
        None
    }
}

/// The fmtp line this endpoint writes for a format of `mime_type` in a description that
/// sends (`sends`) and / or receives (`receives`), an offer or an answer (`is_offer`): the
/// parameters of `line` the media type's table makes usable there (RFC 6184 section 8.2.2,
/// Table 6; RFC 7798 section 7.2.2, Table 1).
///
/// - A receiver capability is not written in a `sendonly` description (RFC 6184 section
///   8.2.2: "These parameters MUST NOT be present when the direction attribute is
///   "sendonly""; RFC 7798 section 7.2.2, the same for `max-lsr` .. `max-fps`, and Table 1's
///   "-" for the rest): this endpoint receives nothing there.
/// - A property or the parameter sets of the stream this endpoint sends are not written in a
///   `recvonly` description (Table 6 and Table 1: "-"): it sends no stream there. H.265's
///   `sprop-segmentation-id` and `sprop-spatial-segmentation-idc` are P in every column and
///   stay.
/// - H.265's `recv-sub-layer-id` is never written in an offer (Table 1: "X: MUST NOT be
///   present"), nor in a `sendonly` answer ("-").
/// - H.264's `level-asymmetry-allowed` is written in every direction although Table 6 marks
///   it "-" for `recvonly` and `sendonly`: the level each direction uses depends on it in
///   both descriptions (RFC 6184 section 8.2.2: "If level-asymmetry-allowed is equal to 0 (or
///   not present) in either the offer or the answer, level asymmetry is not allowed"), and the
///   answer's level is computed with it.
/// - A parameter the table does not name, and every parameter of a `sendrecv` or `inactive`
///   description, is written as given.
pub(crate) fn written_parameters(
    mime_type: &str,
    line: &str,
    sends: bool,
    receives: bool,
    is_offer: bool,
) -> String {
    let Some(table) = parameter_table(mime_type) else {
        return line.to_owned();
    };
    let sendonly = sends && !receives;
    let recvonly = receives && !sends;
    let usable = |parameter: &str| {
        let name = parameter
            .split_once('=')
            .map_or(parameter, |(k, _)| k)
            .trim();
        let Some(row) = table.iter().find(|r| r.name.eq_ignore_ascii_case(name)) else {
            return true;
        };
        match row.role {
            ParameterRole::OfferAnswer => true,
            ParameterRole::OperationPoint if is_offer => false,
            _ => !(sendonly && !row.sendonly || recvonly && !row.recvonly),
        }
    };
    let parameters = || line.split(';').map(str::trim).filter(|p| !p.is_empty());
    if parameters().all(usable) {
        return line.to_owned();
    }
    parameters()
        .filter(|p| usable(p))
        .collect::<Vec<_>>()
        .join(";")
}

/// parse parses an fmtp string based on the MimeType
pub(crate) fn parse(mime_type: &str, line: &str) -> Box<dyn Fmtp> {
    let mut parameters = HashMap::new();
    for p in line.split(';').collect::<Vec<&str>>() {
        let pp: Vec<&str> = p.trim().splitn(2, '=').collect();
        let key = pp[0].to_lowercase();
        let value = if pp.len() > 1 {
            pp[1].to_owned()
        } else {
            String::new()
        };
        parameters.insert(key, value);
    }

    if mime_type.to_uppercase() == "video/h264".to_uppercase() {
        Box::new(H264Fmtp { parameters })
    } else if mime_type.eq_ignore_ascii_case("video/vp9") {
        Box::new(Vp9Fmtp { parameters })
    } else if mime_type.eq_ignore_ascii_case("video/av1") {
        Box::new(Av1Fmtp { parameters })
    } else if mime_type.eq_ignore_ascii_case("video/h265") {
        Box::new(H265Fmtp { parameters })
    } else {
        Box::new(GenericFmtp {
            mime_type: mime_type.to_owned(),
            parameters,
        })
    }
}