Skip to main content

rtci_interceptor/ulpfec/
mod.rs

1//! ULPFEC: generic forward error correction with uneven level protection (RFC 5109).
2//!
3//! A FEC packet is the XOR of a set of media packets, named by a mask relative to a base sequence
4//! number. Protection is organised in **levels**: level 0 covers the RTP header fields and the
5//! first `L0` octets after the fixed header, level 1 the next `L1` octets, and so on, each level
6//! with its own mask. One level whose length is the longest packet is the plain parity code of
7//! RFC 2733; several levels protect the start of a packet more strongly than its end.
8//!
9//! # What is here
10//!
11//! - [`UlpfecPacket`]: the FEC header and the level headers (RFC 5109 7.3, 7.4), read and written.
12//! - [`UlpfecEncoder`]: the protection operation (section 8), for any mask and any levels, with
13//!   the mask rules of 7.4 checked for one packet and, by [`validate_scheme`], across the FEC
14//!   packets of a group.
15//! - [`UlpfecDecoder`]: recovery (section 9), level by level, iterated until nothing more can be
16//!   rebuilt, over a bounded window of media and FEC packets.
17//! - Two carriages (section 14), as a pair of interceptors:
18//!   [`UlpfecSendInterceptor`] / [`UlpfecReceiveInterceptor`].
19//!
20//! # The two carriages
21//!
22//! **Redundant encoding (14.2), what browsers negotiate for video** (`video/red` with
23//! `video/ulpfec`). Every packet of the stream is a RED packet (RFC 2198) on the media SSRC, in
24//! the media stream's sequence number space. A media packet is one primary block. FEC data is
25//! either a RED packet of its own whose only block is the FEC payload type (libwebrtc's form,
26//! [`RedPlacement::OwnPacket`]), or a redundant block ahead of the next media packet's primary
27//! block (the form of RFC 5109 10.3, [`RedPlacement::WithNextMedia`]). The FEC protects the
28//! *virtual* RTP packets: the RED packets with the block header removed and the payload type
29//! replaced by the primary's.
30//!
31//! **Separate stream (14.1).** FEC packets carry the FEC payload type and their own sequence
32//! numbers. The RFC puts that stream in a second RTP session with the media stream's SSRC; a
33//! WebRTC transport is one session, where two sequence spaces under one SSRC cannot coexist
34//! (SRTP keys its replay state on the SSRC). The interceptors therefore send and expect the FEC
35//! stream on the repair SSRC of [`StreamInfo::ssrc_fec`](crate::StreamInfo::ssrc_fec).
36//! [`UlpfecStreamPacketizer`] builds the RFC's own form, FEC packets on the media SSRC, for an
37//! application that does carry them to a separate session.
38//!
39//! # RED
40//!
41//! The RED block reader and writer in this module are the part of RFC 2198 the FEC carriage
42//! needs, kept private apart from [`depacketize_red`]. A general RED codec belongs to `rtci-rtp`.
43
44pub(crate) mod decoder;
45pub(crate) mod encoder;
46pub(crate) mod header;
47pub(crate) mod receiver;
48pub(crate) mod red;
49pub(crate) mod sender;
50
51/// Why ULPFEC data was refused.
52#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53#[non_exhaustive]
54pub enum UlpfecError {
55    /// Fewer octets than the 10-octet FEC header and one level header.
56    TooShort,
57    /// A level header says more payload follows than the packet holds.
58    TruncatedLevel,
59    /// A level protects no packet at all.
60    EmptyMask,
61    /// More protection levels than the decoder accepts.
62    TooManyLevels,
63    /// More than one level in a stream that signalled `onelevelonly=1`.
64    MoreThanOneLevel,
65    /// The encoder was given no level, or a level with no packet.
66    NothingToProtect,
67    /// A sequence number named by a level is not among the media packets given.
68    UnknownSequenceNumber,
69    /// The protected packets span more than 48 sequence numbers.
70    SpanTooWide,
71    /// A media packet is longer than the 16-bit length recovery field can describe, or could not
72    /// be serialised.
73    PacketTooLarge,
74    /// A media packet is protected twice at a level above 0, or twice at level 0 with different
75    /// protection lengths (RFC 5109 7.4 rule a).
76    ProtectedTwice,
77    /// A media packet is protected at a level without being protected at the level below
78    /// (RFC 5109 7.4 rule b).
79    LevelBelowMissing,
80    /// A RED payload whose block headers do not fit the data.
81    MalformedRed,
82    /// A RED block longer than the 10-bit block length allows.
83    RedBlockTooLong,
84    /// The FEC packet names sequence numbers outside the decoder's window.
85    OutsideWindow,
86}
87
88impl std::fmt::Display for UlpfecError {
89    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
90        let text = match self {
91            Self::TooShort => "ULPFEC packet shorter than its headers",
92            Self::TruncatedLevel => "ULPFEC level payload is truncated",
93            Self::EmptyMask => "ULPFEC level protects no packet",
94            Self::TooManyLevels => "ULPFEC packet has too many levels",
95            Self::MoreThanOneLevel => "more than one ULPFEC level with onelevelonly=1",
96            Self::NothingToProtect => "no packet to protect",
97            Self::UnknownSequenceNumber => "protected sequence number is not among the packets",
98            Self::SpanTooWide => "protected packets span more than 48 sequence numbers",
99            Self::PacketTooLarge => "media packet too large to protect",
100            Self::ProtectedTwice => "media packet protected twice at one level",
101            Self::LevelBelowMissing => "media packet not protected at the level below",
102            Self::MalformedRed => "malformed RED payload",
103            Self::RedBlockTooLong => "RED block longer than 1023 octets",
104            Self::OutsideWindow => "ULPFEC packet outside the decoder window",
105        };
106        f.write_str(text)
107    }
108}
109
110impl std::error::Error for UlpfecError {}
111
112/// The value of the `onelevelonly` media type parameter in an `a=fmtp` parameter string
113/// (RFC 5109 13): `true` for `onelevelonly=1`, `false` for `0`, for an absent parameter (its
114/// default) and for any other value.
115///
116/// The input the SDP side has for [`UlpfecSendBuilder::with_one_level_only`] and
117/// [`UlpfecReceiveBuilder::with_one_level_only`].
118pub fn one_level_only_from_fmtp(fmtp: &str) -> bool {
119    fmtp.split(';').any(|parameter| {
120        let mut parts = parameter.splitn(2, '=');
121        let name = parts.next().unwrap_or_default().trim();
122        let value = parts.next().unwrap_or_default().trim();
123        name.eq_ignore_ascii_case("onelevelonly") && value == "1"
124    })
125}
126
127pub use decoder::{UlpfecDecoder, UlpfecDecoderStats};
128pub use encoder::{ProtectionLevel, UlpfecEncoder, UlpfecStreamPacketizer, validate_scheme};
129pub use header::{
130    FEC_HEADER_LENGTH, LONG_MASK_BITS, MAX_LEVELS, SHORT_MASK_BITS, UlpfecLevel, UlpfecPacket,
131};
132pub use receiver::{UlpfecReceiveBuilder, UlpfecReceiveInterceptor, UlpfecRepair};
133pub use red::{RedFecPayload, depacketize_red};
134pub use sender::{RedPlacement, UlpfecSendBuilder, UlpfecSendInterceptor};
135
136#[cfg(test)]
137mod tests {
138    use super::*;
139
140    #[test]
141    fn onelevelonly_is_read_from_an_fmtp_line() {
142        assert!(one_level_only_from_fmtp("onelevelonly=1"));
143        assert!(one_level_only_from_fmtp("foo=bar; OneLevelOnly = 1"));
144        assert!(!one_level_only_from_fmtp("onelevelonly=0"));
145        assert!(!one_level_only_from_fmtp(""), "absent means 0");
146        assert!(!one_level_only_from_fmtp("onelevelonly=2"));
147        assert!(!one_level_only_from_fmtp("xonelevelonly=1"));
148    }
149}