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
#[cfg(test)]
mod h264_test;

use super::*;

/// `profile-level-id` of a format without one (RFC 6184 section 8.1: "the Baseline profile,
/// without additional constraints at Level 1, MUST be inferred").
pub(crate) const DEFAULT_PROFILE_LEVEL_ID: &str = "42000a";

/// `packetization-mode` of a format without one (RFC 6184 section 8.1: "When the value of
/// packetization-mode is equal to 0 or packetization-mode is not present, the single NAL mode
/// MUST be used").
const DEFAULT_PACKETIZATION_MODE: &str = "0";

/// Every media type parameter of H.264 (RFC 6184 section 8.1) with its role and use, as RFC
/// 6184 section 8.2.2 Table 6 gives them ("A receiver SHOULD understand all media type
/// parameters"). What the engine does with each:
///
/// - `profile-level-id`, `packetization-mode` (C): the format's identity ([`H264Fmtp`]
///   `match_fmtp`); the answer keeps the profile and states the level of section 8.2.2
///   (`h264_answer_fmtp`); the mode selects the payloader and depacketizer.
/// - `level-asymmetry-allowed` (O): the answer's level (`h264_answer_fmtp`).
/// - `max-mbps`, `max-fs`, `max-br` (R): the peer's are send limits
///   (`RTCRtpSender::send_restrictions`). `deint-buf-cap` (R): this endpoint states its own
///   (`h264_generated_fmtp`). `max-recv-level`, `max-smbps`, `max-cpb`, `max-dpb`,
///   `redundant-pic-cap`, `max-rcmd-nalu-size`, `sar-understood`, `sar-supported` (R): limits
///   of the encoder, which is the application's; they reach it in the remote description's
///   fmtp line. `in-band-parameter-sets`, `use-level-src-parameter-sets` (R): this
///   endpoint's decide which of the peer's out-of-band sets are read
///   (`h264_received_fmtp`); the peer's `in-band-parameter-sets=1` in an offer has the
///   answer state no out-of-band sets (`h264_answer_fmtp`).
/// - `sprop-interleaving-depth`, `sprop-max-don-diff` (P): the peer's configure the
///   de-interleaving buffer (`RTCRtpCodec::h264_depacketizer`). `sprop-deint-buf-req` (P):
///   the buffer holds `MAX_DEINTERLEAVING_BYTES`, the `deint-buf-cap` this endpoint states,
///   so a stream within it needs nothing more. `sprop-init-buf-time` (P): when decoding may
///   start; the depacketizer's buffer takes it (`H264DeinterleavingBuffer::with_init_buf_time`)
///   and ends initial buffering by it when packets are given with their arrival time
///   (`H264Packet::depacketize_at`, `H264Packet::is_initial_buffering`).
/// - `sprop-parameter-sets`, `sprop-level-parameter-sets` (S): the peer's are kept or left
///   out by the level to use (RFC 6184 section 8.2.2, `h264_received_fmtp`) and decoded for
///   the application's decoder (`RTCRtpCodec::sprop_parameter_sets`); this endpoint never
///   writes `sprop-parameter-sets` (`h264_generated_fmtp`).
///
/// [`written_parameters`] leaves out of a description what its direction cannot use.
pub(crate) const PARAMETERS: &[ParameterUse] = &[
    row("profile-level-id", ParameterRole::Configuration, true, true),
    row(
        "max-recv-level",
        ParameterRole::ReceiverCapability,
        true,
        false,
    ),
    row(
        "packetization-mode",
        ParameterRole::Configuration,
        true,
        true,
    ),
    row(
        "sprop-deint-buf-req",
        ParameterRole::StreamProperty,
        false,
        true,
    ),
    row(
        "sprop-interleaving-depth",
        ParameterRole::StreamProperty,
        false,
        true,
    ),
    row(
        "sprop-max-don-diff",
        ParameterRole::StreamProperty,
        false,
        true,
    ),
    row(
        "sprop-init-buf-time",
        ParameterRole::StreamProperty,
        false,
        true,
    ),
    row("max-mbps", ParameterRole::ReceiverCapability, true, false),
    row("max-smbps", ParameterRole::ReceiverCapability, true, false),
    row("max-fs", ParameterRole::ReceiverCapability, true, false),
    row("max-cpb", ParameterRole::ReceiverCapability, true, false),
    row("max-dpb", ParameterRole::ReceiverCapability, true, false),
    row("max-br", ParameterRole::ReceiverCapability, true, false),
    row(
        "redundant-pic-cap",
        ParameterRole::ReceiverCapability,
        true,
        false,
    ),
    row(
        "deint-buf-cap",
        ParameterRole::ReceiverCapability,
        true,
        false,
    ),
    row(
        "max-rcmd-nalu-size",
        ParameterRole::ReceiverCapability,
        true,
        false,
    ),
    row(
        "sar-understood",
        ParameterRole::ReceiverCapability,
        true,
        false,
    ),
    row(
        "sar-supported",
        ParameterRole::ReceiverCapability,
        true,
        false,
    ),
    row(
        "in-band-parameter-sets",
        ParameterRole::ReceiverCapability,
        true,
        false,
    ),
    row(
        "use-level-src-parameter-sets",
        ParameterRole::ReceiverCapability,
        true,
        false,
    ),
    row(
        "level-asymmetry-allowed",
        ParameterRole::OfferAnswer,
        false,
        false,
    ),
    row(
        "sprop-parameter-sets",
        ParameterRole::ParameterSets,
        false,
        true,
    ),
    row(
        "sprop-level-parameter-sets",
        ParameterRole::ParameterSets,
        false,
        true,
    ),
];

const fn row(
    name: &'static str,
    role: ParameterRole,
    recvonly: bool,
    sendonly: bool,
) -> ParameterUse {
    ParameterUse {
        name,
        role,
        recvonly,
        sendonly,
    }
}

/// RFC 6184 section 8.1, Table 5: the combinations of `profile_idc` and `profile-iop` that
/// stand for the full set of coding tools of one profile, as (profile, profile_idc, mask,
/// value): a `profile-iop` byte `iop` is one of them when `iop & mask == value` (the bits
/// marked `x` in the table are not in the mask). Constrained Baseline is listed first: its
/// patterns are narrower than Baseline's.
const PROFILES: &[(&str, u8, u8, u8)] = &[
    ("CB", 0x42, 0b0100_1111, 0b0100_0000),
    ("CB", 0x4D, 0b1000_1111, 0b1000_0000),
    ("CB", 0x58, 0b1100_1111, 0b1100_0000),
    ("B", 0x42, 0b0100_1111, 0b0000_0000),
    ("B", 0x58, 0b1100_1111, 0b1000_0000),
    ("M", 0x4D, 0b1010_1111, 0b0000_0000),
    ("E", 0x58, 0b1100_1111, 0b0000_0000),
    ("H", 0x64, 0xFF, 0b0000_0000),
    ("H10", 0x6E, 0xFF, 0b0000_0000),
    ("H42", 0x7A, 0xFF, 0b0000_0000),
    ("H44", 0xF4, 0xFF, 0b0000_0000),
    ("H10I", 0x6E, 0xFF, 0b0001_0000),
    ("H42I", 0x7A, 0xFF, 0b0001_0000),
    ("H44I", 0xF4, 0xFF, 0b0001_0000),
    ("C44I", 0x2C, 0xFF, 0b0001_0000),
];

/// The Table 5 profile a `profile_idc` / `profile-iop` pair stands for, if any.
fn table_5_profile(profile_idc: u8, profile_iop: u8) -> Option<&'static str> {
    PROFILES
        .iter()
        .find(|(_, idc, mask, value)| *idc == profile_idc && profile_iop & mask == *value)
        .map(|(profile, ..)| *profile)
}

/// Whether two `profile-level-id` values name the same sub-profile (RFC 6184 section 8.2.2:
/// the level part is not compared). Pairs of Table 5 compare as the profile they stand for,
/// so `42e01f` (Constrained Baseline as Baseline with constraint_set1) is the same as `4d801f`
/// (as Main with constraint_set0); any other pair compares as its two bytes.
fn profile_level_id_matches(a: &str, b: &str) -> bool {
    let decode = |value: &str| -> Option<(u8, u8)> {
        let bytes = hex::decode(value.trim()).ok()?;
        (bytes.len() == 3).then(|| (bytes[0], bytes[1]))
    };
    let (Some((a_idc, a_iop)), Some((b_idc, b_iop))) = (decode(a), decode(b)) else {
        return false;
    };
    match (table_5_profile(a_idc, a_iop), table_5_profile(b_idc, b_iop)) {
        (Some(a), Some(b)) => a == b,
        _ => a_idc == b_idc && a_iop == b_iop,
    }
}

/// An H.264 level as RFC 6184 section 8.1 signals it, in level order: `level_idc` (ten times
/// the level), except Level 1b, "a level higher than Level 1.0 but lower than Level 1.1",
/// which "For the Baseline, Main, and Extended profiles (with profile_idc equal to 66, 77,
/// and 88, respectively) ... is indicated by level_idc equal to 11 (i.e., same as Level 1.1)
/// and constraint_set3_flag equal to 1. For other profiles, Level 1b is indicated by
/// level_idc equal to 9" ("offerers and answerers must check the value of bit 4
/// (constraint_set3_flag) of the middle octet"). Held as twice `level_idc`, Level 1b as 21.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) struct H264Level(u16);

/// constraint_set3_flag, bit 4 of `profile-iop`.
const CONSTRAINT_SET3: u8 = 0x10;

impl H264Level {
    pub(crate) const LEVEL_1B: Self = Self(21);

    /// Baseline, Main and Extended signal Level 1b with constraint_set3_flag.
    fn flags_1b(profile_idc: u8) -> bool {
        matches!(profile_idc, 66 | 77 | 88)
    }

    /// The default level of a `profile-level-id` (three bytes, six hex digits).
    pub(crate) fn of_profile_level_id(profile_level_id: &str) -> Option<Self> {
        let bytes = hex::decode(profile_level_id.trim()).ok()?;
        let [profile_idc, profile_iop, level_idc] = <[u8; 3]>::try_from(bytes).ok()?;
        let is_1b = if Self::flags_1b(profile_idc) {
            level_idc == 11 && profile_iop & CONSTRAINT_SET3 != 0
        } else {
            level_idc == 9
        };
        Some(if is_1b {
            Self::LEVEL_1B
        } else {
            Self(u16::from(level_idc) * 2)
        })
    }

    /// The level a `max-recv-level` value names (`profile-iop` and `level_idc`, four hex
    /// digits; section 8.1: "If the level_idc byte of max-recv-level is equal to 11 and bit 4
    /// of the profile-iop byte of max-recv-level is equal to 1 or if the level_idc byte of
    /// max-recv-level is equal to 9 and bit 4 of the profile-iop byte of max-recv-level is
    /// equal to 0, the highest level the receiver supports is Level 1b").
    pub(crate) fn of_max_recv_level(max_recv_level: &str) -> Option<Self> {
        let bytes = hex::decode(max_recv_level.trim()).ok()?;
        let [profile_iop, level_idc] = <[u8; 2]>::try_from(bytes).ok()?;
        let flag = profile_iop & CONSTRAINT_SET3 != 0;
        Some(if (level_idc == 11 && flag) || (level_idc == 9 && !flag) {
            Self::LEVEL_1B
        } else {
            Self(u16::from(level_idc) * 2)
        })
    }

    /// `profile_level_id` with its level part set to this level, as its profile signals it:
    /// Level 1b of Baseline, Main or Extended sets constraint_set3_flag (and Level 1.1
    /// clears it), Level 1b of another profile is `level_idc` 9. The profile part is kept as
    /// written unless the flag changes. `None` for a value that is not three bytes.
    pub(crate) fn in_profile_level_id(self, profile_level_id: &str) -> Option<String> {
        let id = profile_level_id.trim();
        let bytes = hex::decode(id).ok()?;
        let [profile_idc, profile_iop, _] = <[u8; 3]>::try_from(bytes).ok()?;
        let flags = Self::flags_1b(profile_idc);
        let (iop, level_idc) = if self == Self::LEVEL_1B {
            if flags {
                (profile_iop | CONSTRAINT_SET3, 11)
            } else {
                (profile_iop, 9)
            }
        } else {
            let level_idc = u8::try_from(self.0 / 2).unwrap_or(u8::MAX);
            if flags && level_idc == 11 {
                (profile_iop & !CONSTRAINT_SET3, level_idc)
            } else {
                (profile_iop, level_idc)
            }
        };
        let profile = if iop == profile_iop {
            id[..4].to_owned()
        } else {
            format!("{profile_idc:02x}{iop:02x}")
        };
        Some(format!("{profile}{level_idc:02x}"))
    }
}

#[derive(Debug, PartialEq)]
pub(crate) struct H264Fmtp {
    pub(crate) parameters: HashMap<String, String>,
}

impl Fmtp for H264Fmtp {
    fn mime_type(&self) -> &str {
        "video/h264"
    }

    /// Match returns true if h and b are compatible fmtp descriptions
    /// Based on RFC6184 Section 8.2.2:
    ///   The parameters identifying a media format configuration for H.264
    ///   are profile-level-id and packetization-mode.  These media format
    ///   configuration parameters (except for the level part of profile-
    ///   level-id) MUST be used symmetrically; that is, the answerer MUST
    ///   either maintain all configuration parameters or remove the media
    ///   format (payload type) completely if one or more of the parameter
    ///   values are not supported.
    ///     Informative note: The requirement for symmetric use does not
    ///     apply for the level part of profile-level-id and does not apply
    ///     for the other stream properties and capability parameters.
    fn match_fmtp(&self, f: &dyn Fmtp) -> bool {
        let Some(c) = f.as_any().downcast_ref::<H264Fmtp>() else {
            return false;
        };
        // RFC 6184 section 8.1: an absent parameter has its default value.
        let get = |fmtp: &H264Fmtp, key: &str, default: &'static str| -> String {
            fmtp.parameters
                .get(key)
                .map_or_else(|| default.to_owned(), |v| v.trim().to_owned())
        };
        // RFC 6184 section 8.1: "packetization-mode ... MUST be equal to 0, 1, or 2"; a
        // format with another value is no format this endpoint can send or receive.
        let mode = get(self, "packetization-mode", DEFAULT_PACKETIZATION_MODE);
        ["0", "1", "2"].contains(&mode.as_str())
            && mode == get(c, "packetization-mode", DEFAULT_PACKETIZATION_MODE)
            && profile_level_id_matches(
                &get(self, "profile-level-id", DEFAULT_PROFILE_LEVEL_ID),
                &get(c, "profile-level-id", DEFAULT_PROFILE_LEVEL_ID),
            )
    }

    fn parameter(&self, key: &str) -> Option<&String> {
        self.parameters.get(key)
    }

    fn equal(&self, other: &dyn Fmtp) -> bool {
        other.as_any().downcast_ref::<H264Fmtp>() == Some(self)
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}