Skip to main content

rtci_interceptor/flexfec/rfc8627/
header.rs

1//! The RFC 8627 FEC header: the three variants of section 4.2.2, read and written.
2
3use crate::flexfec::bit_array::BitArray;
4
5/// Octets of RTP header a repair packet recovers from; the protected "payload" starts here.
6pub(crate) const RTP_FIXED_HEADER_SIZE: usize = 12;
7
8/// The recovery fields every R=0 header starts with: P, X, CC, M, PT recovery, length recovery
9/// and TS recovery (Figures 12 and 13).
10pub const FLEXFEC_RECOVERY_SIZE: usize = 8;
11
12/// The most source packets a flexible mask can name: 15 + 31 + 64 bits (section 4.2.2.1).
13pub const FLEXFEC_MAX_MASK_BITS: u32 = 110;
14
15/// The most source streams one repair packet can protect: the CSRC count is four bits.
16pub const FLEXFEC_MAX_PROTECTED_SSRCS: usize = 15;
17
18const R_BIT: u8 = 0x80;
19const F_BIT: u8 = 0x40;
20const K_BIT: u8 = 0x80;
21
22/// Why a repair packet's FEC header cannot be used.
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24#[non_exhaustive]
25pub enum FlexFecHeaderError {
26    /// Shorter than the fields it claims to carry.
27    Truncated,
28    /// R=1 and F=1: reserved, MUST be ignored (section 4.2.2).
29    ReservedVariant,
30    /// An R=0 repair packet whose RTP header has no CSRC: it names no source stream
31    /// (section 4.2.1).
32    NoProtectedSsrc,
33    /// L=0: with D=0 it is reserved and MUST be ignored (section 4.2.2.2); with any other D it
34    /// describes no packet.
35    ZeroColumns,
36    /// No mask bit is set in any block: the packet protects nothing.
37    ProtectsNothing,
38    /// A retransmission whose payload is not an RTP packet (shorter than a fixed RTP header).
39    NotARetransmittedPacket,
40}
41
42impl std::fmt::Display for FlexFecHeaderError {
43    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
44        f.write_str(match self {
45            Self::Truncated => "FlexFEC header is truncated",
46            Self::ReservedVariant => "FlexFEC header has R=1 and F=1, which is reserved",
47            Self::NoProtectedSsrc => "FlexFEC repair packet has no CSRC naming a source stream",
48            Self::ZeroColumns => "FlexFEC header has L=0",
49            Self::ProtectsNothing => "FlexFEC repair packet protects no source packet",
50            Self::NotARetransmittedPacket => "FlexFEC retransmission holds no RTP packet",
51        })
52    }
53}
54
55impl std::error::Error for FlexFecHeaderError {}
56
57/// How one block of a repair packet names the source packets it protects.
58///
59/// Exhaustive: the one F bit selects between the two.
60#[derive(Debug, Clone, Copy, PartialEq, Eq)]
61pub enum FlexFecProtected {
62    /// Flexible mask (R=0, F=0): bit *j* set means the packet `SN base + j` is protected, bit 0
63    /// being the most significant (section 4.2.2.1). Up to 110 bits.
64    Mask(BitArray),
65    /// Fixed L columns and D rows (R=0, F=1; section 4.2.2.2, Figure 14):
66    ///
67    /// - `d <= 1`: row FEC over `SN base, SN base + 1, ..., SN base + (l - 1)` (`d == 1` says
68    ///   column FEC follows, 2-D);
69    /// - `d > 1`: column FEC over `SN base, SN base + l, ..., SN base + (d - 1) * l`.
70    Fixed {
71        /// L, the number of columns. Never 0 in a parsed header.
72        l: u8,
73        /// D, the number of rows.
74        d: u8,
75    },
76}
77
78/// One block of an R=0 FEC header: the source stream (taken from the repair packet's CSRC
79/// list), its SN base, and the mask or L/D that follows.
80#[derive(Debug, Clone, Copy, PartialEq, Eq)]
81pub struct FlexFecBlock {
82    /// The source stream's SSRC: CSRC_i of the repair packet's RTP header.
83    pub ssrc: u32,
84    /// The lowest sequence number of this stream the repair packet protects.
85    pub sn_base: u16,
86    /// Which packets from there.
87    pub protected: FlexFecProtected,
88}
89
90impl FlexFecBlock {
91    /// The offsets from `sn_base` of the packets this block protects, ascending.
92    ///
93    /// At most 255 entries: a mask has 110 bits, a row L <= 255 packets, a column D <= 255.
94    pub fn offsets(&self) -> Vec<u16> {
95        match self.protected {
96            FlexFecProtected::Mask(mask) => (0..FLEXFEC_MAX_MASK_BITS)
97                .filter(|&bit| mask.bit(bit))
98                .map(|bit| bit as u16)
99                .collect(),
100            FlexFecProtected::Fixed { l, d } if d <= 1 => (0..u16::from(l)).collect(),
101            FlexFecProtected::Fixed { l, d } => {
102                (0..u16::from(d)).map(|row| row * u16::from(l)).collect()
103            }
104        }
105    }
106
107    /// The distance from `sn_base` to the last packet protected, plus one: how many sequence
108    /// numbers the block spans. 0 when it protects nothing.
109    pub fn span(&self) -> u32 {
110        self.offsets().last().map_or(0, |&last| u32::from(last) + 1)
111    }
112
113    /// The sequence numbers this block protects, in sending order.
114    pub fn sequence_numbers(&self) -> Vec<u16> {
115        self.offsets()
116            .into_iter()
117            .map(|offset| self.sn_base.wrapping_add(offset))
118            .collect()
119    }
120}
121
122/// A parsed FEC header (section 4.2.2).
123///
124/// Not exhaustive: R=1 F=1 is reserved for a future variant.
125#[derive(Debug, Clone, PartialEq, Eq)]
126#[non_exhaustive]
127pub enum FlexFecHeader {
128    /// R=0: a parity repair packet, with flexible masks (F=0) or fixed L/D (F=1).
129    Repair {
130        /// The first 8 octets as they are on the wire: R, F, then P, X, CC, M and PT recovery,
131        /// length recovery, TS recovery.
132        recovery: [u8; FLEXFEC_RECOVERY_SIZE],
133        /// One block per CSRC of the repair packet, in CSRC order.
134        blocks: Vec<FlexFecBlock>,
135        /// Offset of the repair payload in the RTP payload.
136        payload_offset: usize,
137    },
138    /// R=1, F=0: the RTP payload is one source packet, whole, with R and F where its version
139    /// bits were (section 4.2.2.3, Figure 15).
140    Retransmission,
141}
142
143impl FlexFecHeader {
144    /// Parse the FEC header at the start of a repair packet's RTP `payload`.
145    ///
146    /// `csrc` is the CSRC list of the repair packet's RTP header, which names the protected
147    /// source streams (section 4.2.1); there is one SN base block per entry.
148    pub fn parse(csrc: &[u32], payload: &[u8]) -> Result<Self, FlexFecHeaderError> {
149        let first = *payload.first().ok_or(FlexFecHeaderError::Truncated)?;
150        let retransmission = first & R_BIT != 0;
151        let fixed = first & F_BIT != 0;
152
153        if retransmission {
154            if fixed {
155                return Err(FlexFecHeaderError::ReservedVariant);
156            }
157            if payload.len() < RTP_FIXED_HEADER_SIZE {
158                return Err(FlexFecHeaderError::NotARetransmittedPacket);
159            }
160            return Ok(Self::Retransmission);
161        }
162
163        if csrc.is_empty() {
164            return Err(FlexFecHeaderError::NoProtectedSsrc);
165        }
166        let recovery: [u8; FLEXFEC_RECOVERY_SIZE] = payload
167            .get(..FLEXFEC_RECOVERY_SIZE)
168            .and_then(|bytes| bytes.try_into().ok())
169            .ok_or(FlexFecHeaderError::Truncated)?;
170
171        let mut offset = FLEXFEC_RECOVERY_SIZE;
172        let mut blocks = Vec::with_capacity(csrc.len());
173        for &ssrc in csrc {
174            let word = payload
175                .get(offset..offset + 4)
176                .ok_or(FlexFecHeaderError::Truncated)?;
177            let sn_base = u16::from_be_bytes([word[0], word[1]]);
178            offset += 4;
179
180            let protected = if fixed {
181                let (l, d) = (word[2], word[3]);
182                if l == 0 {
183                    return Err(FlexFecHeaderError::ZeroColumns);
184                }
185                FlexFecProtected::Fixed { l, d }
186            } else {
187                let mut mask = BitArray::new();
188                set_bits(
189                    &mut mask,
190                    0,
191                    15,
192                    u64::from(u16::from_be_bytes([word[2] & !K_BIT, word[3]])),
193                );
194                // k=1: another mask follows; k=0: this was the last (section 4.2.2.1).
195                if word[2] & K_BIT != 0 {
196                    let second = payload
197                        .get(offset..offset + 4)
198                        .ok_or(FlexFecHeaderError::Truncated)?;
199                    offset += 4;
200                    set_bits(
201                        &mut mask,
202                        15,
203                        31,
204                        u64::from(u32::from_be_bytes([
205                            second[0] & !K_BIT,
206                            second[1],
207                            second[2],
208                            second[3],
209                        ])),
210                    );
211                    if second[0] & K_BIT != 0 {
212                        // The third mask is 64 bits and has no k bit.
213                        let third: [u8; 8] = payload
214                            .get(offset..offset + 8)
215                            .and_then(|bytes| bytes.try_into().ok())
216                            .ok_or(FlexFecHeaderError::Truncated)?;
217                        offset += 8;
218                        set_bits(&mut mask, 46, 64, u64::from_be_bytes(third));
219                    }
220                }
221                FlexFecProtected::Mask(mask)
222            };
223
224            blocks.push(FlexFecBlock {
225                ssrc,
226                sn_base,
227                protected,
228            });
229        }
230
231        if blocks.iter().all(|block| block.span() == 0) {
232            return Err(FlexFecHeaderError::ProtectsNothing);
233        }
234
235        Ok(Self::Repair {
236            recovery,
237            blocks,
238            payload_offset: offset,
239        })
240    }
241}
242
243/// Set bits `first .. first + width` of `mask` from the low `width` bits of `value`, most
244/// significant first.
245fn set_bits(mask: &mut BitArray, first: u32, width: u32, value: u64) {
246    for bit in 0..width {
247        if (value >> (width - 1 - bit)) & 1 == 1 {
248            mask.set_bit(first + bit);
249        }
250    }
251}
252
253/// Append the SN base and mask words of one flexible-mask block (Figure 12).
254///
255/// The mask is written at the smallest of the three sizes that holds its highest set bit: 15
256/// bits, 46 bits or 110 bits, with k=1 on every word another one follows.
257pub(crate) fn write_mask_block(out: &mut Vec<u8>, sn_base: u16, mask: &BitArray) {
258    out.extend_from_slice(&sn_base.to_be_bytes());
259
260    let (mask2, mask3) = (mask.mask2(), mask.mask3());
261    let mut first = mask.mask1().to_be_bytes();
262    if mask2 == 0 && mask3 == 0 {
263        out.extend_from_slice(&first);
264        return;
265    }
266    first[0] |= K_BIT;
267    out.extend_from_slice(&first);
268
269    let mut second = mask2.to_be_bytes();
270    if mask3 == 0 {
271        out.extend_from_slice(&second);
272        return;
273    }
274    second[0] |= K_BIT;
275    out.extend_from_slice(&second);
276    out.extend_from_slice(&mask3.to_be_bytes());
277}
278
279/// Append the SN base, L and D of one fixed block (Figure 13).
280pub(crate) fn write_fixed_block(out: &mut Vec<u8>, sn_base: u16, l: u8, d: u8) {
281    out.extend_from_slice(&sn_base.to_be_bytes());
282    out.push(l);
283    out.push(d);
284}
285
286/// The R and F bits of a parity repair packet's first octet: R=0, F as given.
287pub(crate) fn repair_variant_bits(fixed: bool) -> u8 {
288    if fixed { F_BIT } else { 0 }
289}
290
291#[cfg(test)]
292mod tests {
293    use super::*;
294
295    fn mask_of(bits: &[u32]) -> BitArray {
296        let mut mask = BitArray::new();
297        for &bit in bits {
298            mask.set_bit(bit);
299        }
300        mask
301    }
302
303    fn mask_header(sn_base: u16, bits: &[u32]) -> Vec<u8> {
304        let mut out = vec![0x00, 0x60, 0x00, 0x10, 0x11, 0x22, 0x33, 0x44];
305        write_mask_block(&mut out, sn_base, &mask_of(bits));
306        out
307    }
308
309    /// Figure 12 with the 15-bit mask only: 8 octets of recovery fields, SN base, k=0 and the
310    /// mask. 12 octets in all, where draft-03 has 20.
311    #[test]
312    fn a_fifteen_bit_mask_header_is_twelve_octets_with_k_clear() {
313        let header = mask_header(0x1234, &[0, 2, 14]);
314
315        assert_eq!(
316            vec![
317                0x00,
318                0x60,
319                0x00,
320                0x10,
321                0x11,
322                0x22,
323                0x33,
324                0x44, // recovery fields
325                0x12,
326                0x34, // SN base
327                0b0101_0000,
328                0b0000_0001, // k=0, bits 0, 2 and 14
329            ],
330            header
331        );
332    }
333
334    /// k=1 on the first word says the 31-bit mask follows; k=0 on that one ends the list. The
335    /// polarity is the reverse of draft-03's.
336    #[test]
337    fn a_forty_six_bit_mask_sets_k_on_the_first_word_only() {
338        let header = mask_header(7, &[0, 15, 45]);
339
340        assert_eq!(16, header.len());
341        assert_eq!([0b1100_0000, 0x00], header[10..12], "k=1, bit 0");
342        assert_eq!(
343            [0b0100_0000, 0x00, 0x00, 0x01],
344            header[12..16],
345            "k=0, bits 15 and 45"
346        );
347    }
348
349    /// The third mask is a full 64 bits with no k bit: packets 46 to 109, 110 in all.
350    #[test]
351    fn a_hundred_and_ten_bit_mask_ends_with_sixty_four_bits_and_no_k_bit() {
352        let header = mask_header(7, &[0, 46, 109]);
353
354        assert_eq!(24, header.len());
355        assert_ne!(0, header[10] & 0x80, "k=1");
356        assert_ne!(0, header[12] & 0x80, "k=1");
357        assert_eq!(
358            [0x80, 0, 0, 0, 0, 0, 0, 0x01],
359            header[16..24],
360            "bit 46 is the first bit of the word, bit 109 the last"
361        );
362    }
363
364    #[test]
365    fn every_mask_width_parses_back_to_the_bits_written() {
366        for bits in [
367            vec![0u32],
368            vec![0, 14],
369            vec![0, 15],
370            vec![3, 45],
371            vec![0, 46],
372            vec![0, 1, 2, 60, 109],
373            (0..110).collect(),
374        ] {
375            let header = mask_header(65_530, &bits);
376            let parsed = FlexFecHeader::parse(&[0xAABB_CCDD], &header).expect("parses");
377            let FlexFecHeader::Repair {
378                recovery,
379                blocks,
380                payload_offset,
381            } = parsed
382            else {
383                panic!("a repair header");
384            };
385            assert_eq!(header[..8], recovery);
386            assert_eq!(
387                header.len(),
388                payload_offset,
389                "the payload follows the masks"
390            );
391            assert_eq!(1, blocks.len());
392            assert_eq!(0xAABB_CCDD, blocks[0].ssrc);
393            assert_eq!(65_530, blocks[0].sn_base);
394            assert_eq!(
395                bits.iter().map(|&bit| bit as u16).collect::<Vec<_>>(),
396                blocks[0].offsets()
397            );
398        }
399    }
400
401    /// Sequence numbers wrap: SN base 65530 with bit 10 set is packet 4.
402    #[test]
403    fn protected_sequence_numbers_wrap() {
404        let header = mask_header(65_530, &[0, 10]);
405        let FlexFecHeader::Repair { blocks, .. } =
406            FlexFecHeader::parse(&[1], &header).expect("parses")
407        else {
408            panic!("a repair header");
409        };
410        assert_eq!(vec![65_530, 4], blocks[0].sequence_numbers());
411    }
412
413    /// Section 4.2.2.1: with several CSRCs there is one SN base and mask block per CSRC, each of
414    /// its own width.
415    #[test]
416    fn one_block_follows_per_csrc() {
417        let mut header = vec![0u8; 8];
418        write_mask_block(&mut header, 100, &mask_of(&[0, 1]));
419        write_mask_block(&mut header, 9000, &mask_of(&[0, 20]));
420        write_mask_block(&mut header, 5, &mask_of(&[0, 100]));
421        assert_eq!(8 + 4 + 8 + 16, header.len());
422
423        let FlexFecHeader::Repair {
424            blocks,
425            payload_offset,
426            ..
427        } = FlexFecHeader::parse(&[11, 22, 33], &header).expect("parses")
428        else {
429            panic!("a repair header");
430        };
431        assert_eq!(header.len(), payload_offset);
432        assert_eq!(
433            vec![
434                (11, vec![100, 101]),
435                (22, vec![9000, 9020]),
436                (33, vec![5, 105])
437            ],
438            blocks
439                .iter()
440                .map(|block| (block.ssrc, block.sequence_numbers()))
441                .collect::<Vec<_>>()
442        );
443    }
444
445    /// Figure 13: F=1, then SN base, L and D per CSRC.
446    #[test]
447    fn a_fixed_header_carries_l_and_d() {
448        let mut header = vec![repair_variant_bits(true) | 0x20, 0x60, 0, 9, 1, 2, 3, 4];
449        write_fixed_block(&mut header, 0x0102, 4, 3);
450        assert_eq!(vec![0x60, 0x60, 0, 9, 1, 2, 3, 4, 0x01, 0x02, 4, 3], header);
451
452        let FlexFecHeader::Repair {
453            blocks,
454            payload_offset,
455            ..
456        } = FlexFecHeader::parse(&[9], &header).expect("parses")
457        else {
458            panic!("a repair header");
459        };
460        assert_eq!(12, payload_offset);
461        assert_eq!(FlexFecProtected::Fixed { l: 4, d: 3 }, blocks[0].protected);
462    }
463
464    /// Figure 14: D of 0 or 1 is a row of L consecutive packets; D above 1 is a column of D
465    /// packets, L apart.
466    #[test]
467    fn l_and_d_select_a_row_or_a_column() {
468        let block = |l, d| FlexFecBlock {
469            ssrc: 1,
470            sn_base: 65_534,
471            protected: FlexFecProtected::Fixed { l, d },
472        };
473
474        assert_eq!(vec![65_534, 65_535, 0, 1], block(4, 0).sequence_numbers());
475        assert_eq!(vec![65_534, 65_535, 0, 1], block(4, 1).sequence_numbers());
476        assert_eq!(vec![65_534, 2, 6], block(4, 3).sequence_numbers());
477        assert_eq!(vec![65_534], block(1, 0).sequence_numbers(), "L=1 D=0");
478
479        assert_eq!(4, block(4, 1).span());
480        assert_eq!(9, block(4, 3).span());
481        assert_eq!(254 * 255 + 1, block(255, 255).span());
482    }
483
484    /// Section 4.2.2.2: L=0 and D=0 MUST be ignored if received.
485    #[test]
486    fn l_zero_is_refused() {
487        for d in [0u8, 1, 7] {
488            let mut header = vec![repair_variant_bits(true), 0, 0, 0, 0, 0, 0, 0];
489            write_fixed_block(&mut header, 100, 0, d);
490            assert_eq!(
491                Err(FlexFecHeaderError::ZeroColumns),
492                FlexFecHeader::parse(&[1], &header),
493                "L=0 D={d}"
494            );
495        }
496    }
497
498    /// Section 4.2.2: R=1 with F=1 is reserved; receivers MUST ignore these packets.
499    #[test]
500    fn r_and_f_both_set_is_refused() {
501        let header = [0xC0u8; 32];
502        assert_eq!(
503            Err(FlexFecHeaderError::ReservedVariant),
504            FlexFecHeader::parse(&[1], &header)
505        );
506        assert_eq!(
507            Err(FlexFecHeaderError::ReservedVariant),
508            FlexFecHeader::parse(&[], &header)
509        );
510    }
511
512    /// Section 4.2.2.3: R=1 F=0 is a retransmission. The source SSRC is in the FEC header, so
513    /// the CSRC list plays no part.
514    #[test]
515    fn r_set_alone_is_a_retransmission() {
516        let payload = [0x80u8, 96, 0, 1, 0, 0, 0, 2, 0, 0, 0, 3, 0xAA];
517        assert_eq!(
518            Ok(FlexFecHeader::Retransmission),
519            FlexFecHeader::parse(&[], &payload)
520        );
521        assert_eq!(
522            Err(FlexFecHeaderError::NotARetransmittedPacket),
523            FlexFecHeader::parse(&[], &payload[..11]),
524            "shorter than an RTP header"
525        );
526    }
527
528    /// Section 4.2.1: the CSRC list names the protected streams; a parity repair packet with
529    /// none names nothing.
530    #[test]
531    fn a_repair_packet_without_a_csrc_is_refused() {
532        assert_eq!(
533            Err(FlexFecHeaderError::NoProtectedSsrc),
534            FlexFecHeader::parse(&[], &mask_header(1, &[0]))
535        );
536    }
537
538    #[test]
539    fn a_header_cut_short_anywhere_is_refused() {
540        let mut header = vec![0u8; 8];
541        write_mask_block(&mut header, 1, &mask_of(&[0, 109]));
542        write_mask_block(&mut header, 1, &mask_of(&[0, 20]));
543
544        for length in 0..header.len() {
545            assert_eq!(
546                Err(FlexFecHeaderError::Truncated),
547                FlexFecHeader::parse(&[1, 2], &header[..length]),
548                "{length} of {} octets",
549                header.len()
550            );
551        }
552        assert!(FlexFecHeader::parse(&[1, 2], &header).is_ok());
553    }
554
555    #[test]
556    fn a_mask_with_no_bit_set_protects_nothing() {
557        assert_eq!(
558            Err(FlexFecHeaderError::ProtectsNothing),
559            FlexFecHeader::parse(&[1], &mask_header(1, &[]))
560        );
561    }
562}