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//! **Separate RTP session (14.1), the RFC's own form.** A stream bound with
40//! [`StreamInfo::fec_session`](crate::StreamInfo::fec_session) has its FEC in a second RTP
41//! session, on a transport of its own, whatever carriage the builder names. Inside the chain
42//! that FEC stream has the SSRC the field gives; on the FEC session's transport it has the
43//! media stream's SSRC (section 7.2), which whoever drives the chain puts there with
44//! [`FecSessionSsrcMap`](crate::FecSessionSsrcMap). `rtci`'s peer connection does both for a
45//! FEC m= section grouped with the media's.
46//!
47//! # RED
48//!
49//! The RED block reader and writer in this module are the part of RFC 2198 the FEC carriage
50//! needs, kept private apart from [`depacketize_red`]. A general RED codec belongs to `rtci-rtp`.
51
52pub(crate) mod decoder;
53pub(crate) mod encoder;
54pub(crate) mod header;
55pub(crate) mod receiver;
56pub(crate) mod red;
57pub(crate) mod sender;
58
59/// Why ULPFEC data was refused.
60#[derive(Debug, Clone, Copy, PartialEq, Eq)]
61#[non_exhaustive]
62pub enum UlpfecError {
63 /// Fewer octets than the 10-octet FEC header and one level header.
64 TooShort,
65 /// A level header says more payload follows than the packet holds.
66 TruncatedLevel,
67 /// A level protects no packet at all.
68 EmptyMask,
69 /// More protection levels than the decoder accepts.
70 TooManyLevels,
71 /// More than one level in a stream that signalled `onelevelonly=1`.
72 MoreThanOneLevel,
73 /// The encoder was given no level, or a level with no packet.
74 NothingToProtect,
75 /// A sequence number named by a level is not among the media packets given.
76 UnknownSequenceNumber,
77 /// The protected packets span more than 48 sequence numbers.
78 SpanTooWide,
79 /// A media packet is longer than the 16-bit length recovery field can describe, or could not
80 /// be serialised.
81 PacketTooLarge,
82 /// A media packet is protected twice at a level above 0, or twice at level 0 with different
83 /// protection lengths (RFC 5109 7.4 rule a).
84 ProtectedTwice,
85 /// A media packet is protected at a level without being protected at the level below
86 /// (RFC 5109 7.4 rule b).
87 LevelBelowMissing,
88 /// A RED payload whose block headers do not fit the data.
89 MalformedRed,
90 /// A RED block longer than the 10-bit block length allows.
91 RedBlockTooLong,
92 /// The FEC packet names sequence numbers outside the decoder's window.
93 OutsideWindow,
94}
95
96impl std::fmt::Display for UlpfecError {
97 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
98 let text = match self {
99 Self::TooShort => "ULPFEC packet shorter than its headers",
100 Self::TruncatedLevel => "ULPFEC level payload is truncated",
101 Self::EmptyMask => "ULPFEC level protects no packet",
102 Self::TooManyLevels => "ULPFEC packet has too many levels",
103 Self::MoreThanOneLevel => "more than one ULPFEC level with onelevelonly=1",
104 Self::NothingToProtect => "no packet to protect",
105 Self::UnknownSequenceNumber => "protected sequence number is not among the packets",
106 Self::SpanTooWide => "protected packets span more than 48 sequence numbers",
107 Self::PacketTooLarge => "media packet too large to protect",
108 Self::ProtectedTwice => "media packet protected twice at one level",
109 Self::LevelBelowMissing => "media packet not protected at the level below",
110 Self::MalformedRed => "malformed RED payload",
111 Self::RedBlockTooLong => "RED block longer than 1023 octets",
112 Self::OutsideWindow => "ULPFEC packet outside the decoder window",
113 };
114 f.write_str(text)
115 }
116}
117
118impl std::error::Error for UlpfecError {}
119
120/// The value of the `onelevelonly` media type parameter in an `a=fmtp` parameter string
121/// (RFC 5109 13): `true` for `onelevelonly=1`, `false` for `0`, for an absent parameter (its
122/// default) and for any other value.
123///
124/// The input the SDP side has for [`UlpfecSendBuilder::with_one_level_only`] and
125/// [`UlpfecReceiveBuilder::with_one_level_only`].
126pub fn one_level_only_from_fmtp(fmtp: &str) -> bool {
127 fmtp.split(';').any(|parameter| {
128 let mut parts = parameter.splitn(2, '=');
129 let name = parts.next().unwrap_or_default().trim();
130 let value = parts.next().unwrap_or_default().trim();
131 name.eq_ignore_ascii_case("onelevelonly") && value == "1"
132 })
133}
134
135pub use decoder::{UlpfecDecoder, UlpfecDecoderStats};
136pub use encoder::{ProtectionLevel, UlpfecEncoder, UlpfecStreamPacketizer, validate_scheme};
137pub use header::{
138 FEC_HEADER_LENGTH, LONG_MASK_BITS, MAX_LEVELS, SHORT_MASK_BITS, UlpfecLevel, UlpfecPacket,
139};
140pub use receiver::{
141 FecSessionPacket, UlpfecReceiveBuilder, UlpfecReceiveInterceptor, UlpfecReceiveStats,
142 UlpfecRepair,
143};
144pub use red::{RedFecPayload, depacketize_red};
145pub use sender::{RedPlacement, UlpfecSendBuilder, UlpfecSendInterceptor};
146
147#[cfg(test)]
148mod tests {
149 use super::*;
150
151 #[test]
152 fn onelevelonly_is_read_from_an_fmtp_line() {
153 assert!(one_level_only_from_fmtp("onelevelonly=1"));
154 assert!(one_level_only_from_fmtp("foo=bar; OneLevelOnly = 1"));
155 assert!(!one_level_only_from_fmtp("onelevelonly=0"));
156 assert!(!one_level_only_from_fmtp(""), "absent means 0");
157 assert!(!one_level_only_from_fmtp("onelevelonly=2"));
158 assert!(!one_level_only_from_fmtp("xonelevelonly=1"));
159 }
160}
161
162/// The header extensions whose values libwebrtc writes after its FEC was computed, and zeroes
163/// in its receiver's copies (`RtpPacket::ZeroMutableExtensions`): the transport-wide sequence
164/// number, abs-send-time and toffset (RFC 5450).
165pub(crate) const MUTABLE_EXTENSION_URIS: [&str; 3] = [
166 "http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",
167 "http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",
168 "urn:ietf:params:rtp-hdrext:toffset",
169];
170
171/// The ids `info` negotiated [`MUTABLE_EXTENSION_URIS`] under.
172pub(crate) fn mutable_extension_ids(info: &crate::StreamInfo) -> Vec<u8> {
173 info.rtp_header_extensions
174 .iter()
175 .filter(|extension| MUTABLE_EXTENSION_URIS.contains(&extension.uri.as_str()))
176 .filter_map(|extension| u8::try_from(extension.id).ok())
177 .collect()
178}
179
180/// `packet` with the values of the extensions `ids` zeroed (their lengths kept).
181pub(crate) fn with_extensions_zeroed(packet: &rtp::Packet, ids: &[u8]) -> rtp::Packet {
182 let mut copy = packet.clone();
183 for extension in copy.header.extensions.iter_mut() {
184 if ids.contains(&extension.id) {
185 extension.payload = bytes::Bytes::from(vec![0u8; extension.payload.len()]);
186 }
187 }
188 copy
189}