Skip to main content

rtci_interceptor/ulpfec/
header.rs

1//! The ULPFEC payload: FEC header, level headers and level payloads (RFC 5109 7.3, 7.4).
2
3use super::UlpfecError;
4use bytes::{BufMut, Bytes, BytesMut};
5
6/// Octets of the FEC header (RFC 5109 7.3).
7pub const FEC_HEADER_LENGTH: usize = 10;
8
9/// Packets a short mask describes (L = 0).
10pub const SHORT_MASK_BITS: usize = 16;
11
12/// Packets a long mask describes (L = 1).
13pub const LONG_MASK_BITS: usize = 48;
14
15/// The most protection levels read from one FEC packet.
16///
17/// The RFC sets no limit; a level costs at least four octets, so without one a single packet could
18/// declare several hundred empty levels and make every recovery pass walk them.
19pub const MAX_LEVELS: usize = 32;
20
21/// One protection level of a FEC packet: its mask and its payload (RFC 5109 7.4).
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub struct UlpfecLevel {
24    /// Which packets the level protects: bit `i` (bit 0 the least significant) stands for the
25    /// packet with sequence number `SN base + i`. On the wire the order is the reverse, `i = 0`
26    /// being the most significant bit of the mask field.
27    pub mask: u64,
28    /// The level's payload; its length is the level's protection length.
29    pub payload: Bytes,
30}
31
32impl UlpfecLevel {
33    /// Whether the packet `SN base + offset` is protected at this level.
34    pub fn protects(&self, offset: usize) -> bool {
35        offset < LONG_MASK_BITS && self.mask & (1u64 << offset) != 0
36    }
37
38    /// The offsets from the SN base of the packets this level protects, ascending.
39    pub fn offsets(&self) -> impl Iterator<Item = usize> + '_ {
40        (0..LONG_MASK_BITS).filter(|offset| self.protects(*offset))
41    }
42}
43
44/// A parsed ULPFEC payload: what follows the RTP header of a FEC packet, or what a RED block of
45/// the FEC payload type holds.
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub struct UlpfecPacket {
48    /// The L bit: masks are 48 bits long instead of 16.
49    pub long_mask: bool,
50    /// P recovery.
51    pub padding_recovery: bool,
52    /// X recovery.
53    pub extension_recovery: bool,
54    /// CC recovery (4 bits).
55    pub csrc_count_recovery: u8,
56    /// M recovery.
57    pub marker_recovery: bool,
58    /// PT recovery (7 bits).
59    pub payload_type_recovery: u8,
60    /// The lowest sequence number protected at any level.
61    pub sn_base: u16,
62    /// TS recovery.
63    pub timestamp_recovery: u32,
64    /// Length recovery: the XOR of the protected packets' lengths after the fixed RTP header.
65    pub length_recovery: u16,
66    /// The levels, level 0 first. A packet that holds level `p` holds every level below it
67    /// (RFC 5109 7.4 rule c), which the layout guarantees: levels are not numbered on the wire,
68    /// they are counted.
69    pub levels: Vec<UlpfecLevel>,
70}
71
72impl UlpfecPacket {
73    /// Parse a ULPFEC payload.
74    ///
75    /// The E bit is ignored (7.3). Levels are read until the payload ends; a level whose payload
76    /// is cut short, a level with an empty mask and trailing octets too few for a level header are
77    /// all refused, because a packet that is wrong about its own layout cannot be trusted to name
78    /// what it protects.
79    pub fn parse(payload: &[u8]) -> Result<Self, UlpfecError> {
80        if payload.len() < FEC_HEADER_LENGTH + 4 {
81            return Err(UlpfecError::TooShort);
82        }
83        let long_mask = payload[0] & 0x40 != 0;
84        let level_header_length = if long_mask { 8 } else { 4 };
85
86        let mut levels = Vec::new();
87        let mut rest = &payload[FEC_HEADER_LENGTH..];
88        while !rest.is_empty() {
89            if levels.len() == MAX_LEVELS {
90                return Err(UlpfecError::TooManyLevels);
91            }
92            if rest.len() < level_header_length {
93                return Err(UlpfecError::TooShort);
94            }
95            let protection_length = usize::from(u16::from_be_bytes([rest[0], rest[1]]));
96            let mask = read_mask(&rest[2..level_header_length]);
97            if mask == 0 {
98                return Err(UlpfecError::EmptyMask);
99            }
100            rest = &rest[level_header_length..];
101            if rest.len() < protection_length {
102                return Err(UlpfecError::TruncatedLevel);
103            }
104            levels.push(UlpfecLevel {
105                mask,
106                payload: Bytes::copy_from_slice(&rest[..protection_length]),
107            });
108            rest = &rest[protection_length..];
109        }
110
111        Ok(Self {
112            long_mask,
113            padding_recovery: payload[0] & 0x20 != 0,
114            extension_recovery: payload[0] & 0x10 != 0,
115            csrc_count_recovery: payload[0] & 0x0F,
116            marker_recovery: payload[1] & 0x80 != 0,
117            payload_type_recovery: payload[1] & 0x7F,
118            sn_base: u16::from_be_bytes([payload[2], payload[3]]),
119            timestamp_recovery: u32::from_be_bytes([
120                payload[4], payload[5], payload[6], payload[7],
121            ]),
122            length_recovery: u16::from_be_bytes([payload[8], payload[9]]),
123            levels,
124        })
125    }
126
127    /// Serialise: the FEC header, then each level's header and payload.
128    ///
129    /// The E bit is written 0 (7.3). A short mask keeps offsets 0 to 15 only; the encoder sets
130    /// [`long_mask`](Self::long_mask) whenever an offset beyond them is protected.
131    pub fn marshal(&self) -> Bytes {
132        let level_header_length = if self.long_mask { 8 } else { 4 };
133        let size = FEC_HEADER_LENGTH
134            + self
135                .levels
136                .iter()
137                .map(|level| level_header_length + level.payload.len())
138                .sum::<usize>();
139        let mut out = BytesMut::with_capacity(size);
140        out.put_u8(
141            (u8::from(self.long_mask) << 6)
142                | (u8::from(self.padding_recovery) << 5)
143                | (u8::from(self.extension_recovery) << 4)
144                | (self.csrc_count_recovery & 0x0F),
145        );
146        out.put_u8((u8::from(self.marker_recovery) << 7) | (self.payload_type_recovery & 0x7F));
147        out.put_u16(self.sn_base);
148        out.put_u32(self.timestamp_recovery);
149        out.put_u16(self.length_recovery);
150        for level in &self.levels {
151            // A level payload longer than the field can say is not something the encoder builds;
152            // saturating keeps a hand-built packet from wrapping to a short length.
153            out.put_u16(u16::try_from(level.payload.len()).unwrap_or(u16::MAX));
154            write_mask(&mut out, level.mask, self.long_mask);
155            out.put_slice(&level.payload);
156        }
157        out.freeze()
158    }
159
160    /// The recovery bit string of the FEC header (RFC 5109 9.1 step 2), in the layout the
161    /// protected bit string of a media packet has: the first eight octets of an RTP header, then
162    /// the length. The version bits and the sequence number hold nothing.
163    pub(crate) fn header_bit_string(&self) -> [u8; 10] {
164        let mut bits = [0u8; 10];
165        bits[0] = (u8::from(self.padding_recovery) << 5)
166            | (u8::from(self.extension_recovery) << 4)
167            | (self.csrc_count_recovery & 0x0F);
168        bits[1] = (u8::from(self.marker_recovery) << 7) | (self.payload_type_recovery & 0x7F);
169        bits[4..8].copy_from_slice(&self.timestamp_recovery.to_be_bytes());
170        bits[8..10].copy_from_slice(&self.length_recovery.to_be_bytes());
171        bits
172    }
173
174    /// Where level `index` starts in a protected packet, counted from the end of the fixed RTP
175    /// header: the sum of the protection lengths of the levels below it (RFC 5109 8.2, `Sn`).
176    pub(crate) fn level_offset(&self, index: usize) -> usize {
177        self.levels[..index]
178            .iter()
179            .map(|level| level.payload.len())
180            .sum()
181    }
182}
183
184/// Wire mask (16 or 48 bits, offset 0 most significant) to offset bits.
185fn read_mask(wire: &[u8]) -> u64 {
186    let mut mask = 0u64;
187    for (index, byte) in wire.iter().enumerate() {
188        for bit in 0..8 {
189            if byte & (0x80 >> bit) != 0 {
190                mask |= 1u64 << (index * 8 + bit);
191            }
192        }
193    }
194    mask
195}
196
197/// Offset bits to the wire mask.
198fn write_mask(out: &mut BytesMut, mask: u64, long_mask: bool) {
199    let length = if long_mask { 6 } else { 2 };
200    for index in 0..length {
201        let mut byte = 0u8;
202        for bit in 0..8 {
203            if mask & (1u64 << (index * 8 + bit)) != 0 {
204                byte |= 0x80 >> bit;
205            }
206        }
207        out.put_u8(byte);
208    }
209}
210
211#[cfg(test)]
212mod tests {
213    use super::*;
214
215    fn packet(long_mask: bool, levels: Vec<UlpfecLevel>) -> UlpfecPacket {
216        UlpfecPacket {
217            long_mask,
218            padding_recovery: true,
219            extension_recovery: false,
220            csrc_count_recovery: 0x0A,
221            marker_recovery: true,
222            payload_type_recovery: 0x55,
223            sn_base: 0xFFFE,
224            timestamp_recovery: 0x0102_0304,
225            length_recovery: 0x0506,
226            levels,
227        }
228    }
229
230    #[test]
231    fn the_fec_header_is_ten_octets_in_the_order_of_figure_3() {
232        let wire = packet(
233            false,
234            vec![UlpfecLevel {
235                mask: 0b101,
236                payload: Bytes::from_static(&[9, 8, 7]),
237            }],
238        )
239        .marshal();
240        assert_eq!(
241            &[
242                0x2A, 0xD5, 0xFF, 0xFE, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, // FEC header
243                0x00, 0x03, 0xA0, 0x00, // level 0: length 3, packets base+0 and base+2
244                9, 8, 7
245            ],
246            &wire[..]
247        );
248    }
249
250    #[test]
251    fn a_long_mask_sets_the_l_bit_and_takes_six_octets() {
252        let original = packet(
253            true,
254            vec![UlpfecLevel {
255                mask: (1 << 47) | (1 << 16) | 1,
256                payload: Bytes::from_static(&[1]),
257            }],
258        );
259        let wire = original.marshal();
260        assert_eq!(0x40, wire[0] & 0x40, "L bit");
261        assert_eq!(&[0x80, 0x00, 0x80, 0x00, 0x00, 0x01], &wire[12..18]);
262        assert_eq!(FEC_HEADER_LENGTH + 8 + 1, wire.len());
263        assert_eq!(original, UlpfecPacket::parse(&wire).unwrap());
264    }
265
266    #[test]
267    fn the_e_bit_is_sent_as_zero() {
268        let wire = packet(
269            true,
270            vec![UlpfecLevel {
271                mask: 1,
272                payload: Bytes::new(),
273            }],
274        )
275        .marshal();
276        assert_eq!(0, wire[0] & 0x80);
277    }
278
279    #[test]
280    fn a_received_e_bit_is_ignored() {
281        let original = packet(
282            false,
283            vec![UlpfecLevel {
284                mask: 1,
285                payload: Bytes::from_static(&[1, 2]),
286            }],
287        );
288        let mut wire = original.marshal().to_vec();
289        wire[0] |= 0x80;
290        assert_eq!(original, UlpfecPacket::parse(&wire).unwrap());
291    }
292
293    #[test]
294    fn several_levels_follow_each_other() {
295        let original = packet(
296            false,
297            vec![
298                UlpfecLevel {
299                    mask: 0b0011,
300                    payload: Bytes::from_static(&[1, 2, 3]),
301                },
302                UlpfecLevel {
303                    mask: 0b1111,
304                    payload: Bytes::from_static(&[4, 5]),
305                },
306            ],
307        );
308        let parsed = UlpfecPacket::parse(&original.marshal()).unwrap();
309        assert_eq!(original, parsed);
310        assert_eq!(0, parsed.level_offset(0));
311        assert_eq!(3, parsed.level_offset(1));
312        assert_eq!(
313            vec![0, 1, 2, 3],
314            parsed.levels[1].offsets().collect::<Vec<_>>()
315        );
316    }
317
318    #[test]
319    fn a_level_cut_short_is_refused() {
320        let wire = packet(
321            false,
322            vec![UlpfecLevel {
323                mask: 1,
324                payload: Bytes::from_static(&[1, 2, 3, 4]),
325            }],
326        )
327        .marshal();
328        assert_eq!(
329            Err(UlpfecError::TruncatedLevel),
330            UlpfecPacket::parse(&wire[..wire.len() - 1])
331        );
332    }
333
334    #[test]
335    fn a_packet_without_a_level_header_is_refused() {
336        assert_eq!(Err(UlpfecError::TooShort), UlpfecPacket::parse(&[0u8; 10]));
337        assert_eq!(Err(UlpfecError::TooShort), UlpfecPacket::parse(&[]));
338        // L = 1 needs eight octets of level header.
339        let mut wire = [0u8; 14];
340        wire[0] = 0x40;
341        assert_eq!(Err(UlpfecError::TooShort), UlpfecPacket::parse(&wire));
342    }
343
344    #[test]
345    fn a_level_that_protects_nothing_is_refused() {
346        let wire = [0u8; 14];
347        assert_eq!(Err(UlpfecError::EmptyMask), UlpfecPacket::parse(&wire));
348    }
349
350    #[test]
351    fn levels_beyond_the_limit_are_refused() {
352        let levels = vec![
353            UlpfecLevel {
354                mask: 1,
355                payload: Bytes::new(),
356            };
357            MAX_LEVELS + 1
358        ];
359        let wire = packet(false, levels).marshal();
360        assert_eq!(Err(UlpfecError::TooManyLevels), UlpfecPacket::parse(&wire));
361    }
362}