Skip to main content

rtci_interceptor/flexfec/rfc8627/
encoder.rs

1//! RFC 8627 repair packet construction (section 6.2) and retransmission (section 4.2.2.3).
2
3use super::header::{
4    FLEXFEC_MAX_MASK_BITS, FLEXFEC_MAX_PROTECTED_SSRCS, FLEXFEC_RECOVERY_SIZE,
5    RTP_FIXED_HEADER_SIZE, repair_variant_bits, write_fixed_block, write_mask_block,
6};
7use crate::flexfec::bit_array::BitArray;
8use crate::flexfec::coverage::ProtectionCoverage;
9use shared::marshal::{Marshal, MarshalSize};
10
11/// How a repair packet names the source packets it protects.
12///
13/// Exhaustive: the one F bit selects between the two.
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum FlexFecLayout {
16    /// Flexible mask (R=0, F=0): any set of packets within 110 sequence numbers of the lowest.
17    Mask,
18    /// Fixed L columns and D rows (R=0, F=1). The source packets handed over must be exactly
19    /// the row (`d <= 1`: L consecutive packets) or the column (`d > 1`: D packets, L apart)
20    /// that L and D describe from the lowest sequence number.
21    Fixed {
22        /// L, the number of columns; not 0.
23        l: u8,
24        /// D, the number of rows.
25        d: u8,
26    },
27}
28
29/// The shape of the FEC a sender applies to each block of consecutive source packets
30/// (RFC 8627 section 1.1).
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32#[non_exhaustive]
33pub enum FlexFecProtection {
34    /// Flexible masks: blocks of `media_packets` packets, each protected by `fec_packets`
35    /// interleaved repair packets (the first covers packets 0, n, 2n, ..., the second 1, n+1,
36    /// ...). At most 110 packets per block.
37    Mask {
38        /// Source packets per block, 1 to 110.
39        media_packets: u32,
40        /// Repair packets per block.
41        fec_packets: u32,
42    },
43    /// 1-D non-interleaved (row) FEC: one repair packet per `l` consecutive packets
44    /// (section 1.1.1; sent as L=`l`, D=0). Recovers one loss per row.
45    Row {
46        /// L, packets per row; not 0.
47        l: u8,
48    },
49    /// 1-D interleaved (column) FEC: blocks of `l * d` packets, one repair packet per column
50    /// (section 1.1.2; sent as L=`l`, D=`d`). Recovers a burst of up to `l` packets.
51    Column {
52        /// L, the number of columns; not 0.
53        l: u8,
54        /// D, packets per column; at least 2.
55        d: u8,
56    },
57    /// 2-D FEC: blocks of `l * d` packets, one repair packet per row (L=`l`, D=1) and one per
58    /// column (L=`l`, D=`d`), rows first (section 1.1.4).
59    RowAndColumn {
60        /// L, the number of columns; not 0.
61        l: u8,
62        /// D, the number of rows; at least 2.
63        d: u8,
64    },
65}
66
67impl FlexFecProtection {
68    /// How many consecutive source packets make one block; 0 when the shape is not usable.
69    pub fn block_len(&self) -> usize {
70        match *self {
71            Self::Mask {
72                media_packets,
73                fec_packets,
74            } => {
75                if (1..=FLEXFEC_MAX_MASK_BITS).contains(&media_packets) && fec_packets > 0 {
76                    media_packets as usize
77                } else {
78                    0
79                }
80            }
81            Self::Row { l } => usize::from(l),
82            Self::Column { l, d } | Self::RowAndColumn { l, d } => {
83                if l == 0 || d < 2 {
84                    0
85                } else {
86                    usize::from(l) * usize::from(d)
87                }
88            }
89        }
90    }
91
92    /// How many repair packets one block yields.
93    pub fn repair_packets_per_block(&self) -> usize {
94        if self.block_len() == 0 {
95            return 0;
96        }
97        match *self {
98            Self::Mask {
99                media_packets,
100                fec_packets,
101            } => fec_packets.min(media_packets) as usize,
102            Self::Row { .. } => 1,
103            Self::Column { l, .. } => usize::from(l),
104            Self::RowAndColumn { l, d } => usize::from(l) + usize::from(d),
105        }
106    }
107}
108
109/// Why a repair packet could not be built.
110#[derive(Debug, Clone, Copy, PartialEq, Eq)]
111#[non_exhaustive]
112pub enum FlexFecEncodeError {
113    /// No source packet was given.
114    NothingToProtect,
115    /// More than 15 source streams: the CSRC count is four bits (section 4.2.1).
116    TooManySsrcs,
117    /// A stream's packets span more than 110 sequence numbers, which no mask can name.
118    MaskTooNarrow,
119    /// The same sequence number of one stream was given twice.
120    DuplicateSequenceNumber,
121    /// The packets of a stream are not the row or column that L and D describe, or L is 0.
122    NotTheFixedBlock,
123    /// A source packet is longer than the 16-bit length recovery field can express.
124    SourceTooLong,
125    /// A source packet is not RTP version 2, the only version the format supports
126    /// (section 6.2).
127    NotVersion2,
128    /// A source packet could not be serialized.
129    Marshal,
130}
131
132impl std::fmt::Display for FlexFecEncodeError {
133    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
134        f.write_str(match self {
135            Self::NothingToProtect => "no source packet to protect",
136            Self::TooManySsrcs => "more than 15 source streams in one repair packet",
137            Self::MaskTooNarrow => "source packets span more than 110 sequence numbers",
138            Self::DuplicateSequenceNumber => "a source packet was given twice",
139            Self::NotTheFixedBlock => "source packets are not the row or column L and D describe",
140            Self::SourceTooLong => "a source packet is too long for the length recovery field",
141            Self::NotVersion2 => "a source packet is not RTP version 2",
142            Self::Marshal => "a source packet could not be serialized",
143        })
144    }
145}
146
147impl std::error::Error for FlexFecEncodeError {}
148
149/// The 80-bit FEC bit string header and the payload bit string of section 6.2, accumulated by
150/// XOR over the source packets a repair packet protects.
151#[derive(Debug, Default)]
152pub(crate) struct Parity {
153    /// First 16 bits of the RTP header, length recovery, TS recovery.
154    pub(crate) recovery: [u8; FLEXFEC_RECOVERY_SIZE],
155    /// Everything after the fixed 12-byte header, shorter packets padded with zeros at the end.
156    pub(crate) payload: Vec<u8>,
157}
158
159impl Parity {
160    /// XOR one source packet, as its wire octets, into the parity.
161    ///
162    /// `wire` is at least a fixed RTP header long; the caller checks.
163    pub(crate) fn add(&mut self, wire: &[u8]) {
164        let length = (wire.len() - RTP_FIXED_HEADER_SIZE) as u16;
165        self.recovery[0] ^= wire[0];
166        self.recovery[1] ^= wire[1];
167        self.recovery[2] ^= (length >> 8) as u8;
168        self.recovery[3] ^= length as u8;
169        for (target, &octet) in self.recovery[4..8].iter_mut().zip(&wire[4..8]) {
170            *target ^= octet;
171        }
172
173        let rest = &wire[RTP_FIXED_HEADER_SIZE..];
174        if self.payload.len() < rest.len() {
175            self.payload.resize(rest.len(), 0);
176        }
177        for (target, &source) in self.payload.iter_mut().zip(rest) {
178            *target ^= source;
179        }
180    }
181}
182
183/// A source packet as it is on the wire.
184fn wire_of(packet: &rtp::Packet) -> Result<Vec<u8>, FlexFecEncodeError> {
185    if packet.header.version != 2 {
186        return Err(FlexFecEncodeError::NotVersion2);
187    }
188    let size = packet.marshal_size();
189    if size < RTP_FIXED_HEADER_SIZE || size - RTP_FIXED_HEADER_SIZE > usize::from(u16::MAX) {
190        return Err(FlexFecEncodeError::SourceTooLong);
191    }
192    let mut wire = vec![0u8; size];
193    packet
194        .marshal_to(&mut wire)
195        .map_err(|_| FlexFecEncodeError::Marshal)?;
196    Ok(wire)
197}
198
199/// The lowest of `sequence_numbers` taking wrap-around into account: the one every other is
200/// ahead of by less than half the sequence space.
201fn lowest_sequence_number(sequence_numbers: &[u16]) -> u16 {
202    let mut lowest = sequence_numbers[0];
203    for &sequence_number in &sequence_numbers[1..] {
204        if lowest.wrapping_sub(sequence_number) < 0x8000 {
205            lowest = sequence_number;
206        }
207    }
208    lowest
209}
210
211/// Builds RFC 8627 FlexFEC repair packets: the format negotiated as `flexfec` (`video/flexfec`
212/// and the other three media types of RFC 8627 section 5.1), not `flexfec-03`.
213///
214/// One encoder is one repair stream: its own SSRC, payload type and sequence numbers. It may
215/// protect several source streams (section 4.2.2.1), which it names in the CSRC list of each
216/// repair packet.
217#[derive(Debug)]
218pub struct FlexFecEncoder {
219    payload_type: u8,
220    ssrc: u32,
221    next_sequence_number: u16,
222}
223
224impl FlexFecEncoder {
225    /// A repair-stream encoder sending `payload_type` on `ssrc`, its sequence numbers starting
226    /// at 0 until [`with_base_sequence_number`](Self::with_base_sequence_number) says otherwise.
227    pub fn new(payload_type: u8, ssrc: u32) -> Self {
228        Self {
229            payload_type,
230            ssrc,
231            next_sequence_number: 0,
232        }
233    }
234
235    /// Start the repair stream's sequence numbers at `sequence_number`. Section 4.2.1 wants the
236    /// initial value random; the send interceptor draws one.
237    pub fn with_base_sequence_number(mut self, sequence_number: u16) -> Self {
238        self.next_sequence_number = sequence_number;
239        self
240    }
241
242    /// The sequence number the next repair packet will carry.
243    pub fn next_sequence_number(&self) -> u16 {
244        self.next_sequence_number
245    }
246
247    /// The RTP header of the next packet of the repair stream (section 4.2.1): version 2, no
248    /// marker, the CSRC list naming the protected streams, the caller's send-clock timestamp.
249    fn repair_packet(&mut self, csrc: Vec<u32>, timestamp: u32, payload: Vec<u8>) -> rtp::Packet {
250        let sequence_number = self.next_sequence_number;
251        self.next_sequence_number = self.next_sequence_number.wrapping_add(1);
252        rtp::Packet {
253            header: rtp::header::Header {
254                version: 2,
255                marker: false,
256                payload_type: self.payload_type,
257                sequence_number,
258                timestamp,
259                ssrc: self.ssrc,
260                csrc,
261                ..Default::default()
262            },
263            payload: payload.into(),
264        }
265    }
266
267    /// Build one parity repair packet protecting exactly `sources`, stamped with `timestamp`
268    /// (the repair stream's RTP timestamp for the instant it is sent, section 4.2.1).
269    ///
270    /// `sources` may belong to several streams, up to 15: each gets a CSRC entry and its own SN
271    /// base block, in order of first appearance. Order within a stream does not matter.
272    pub fn encode(
273        &mut self,
274        layout: FlexFecLayout,
275        sources: &[rtp::Packet],
276        timestamp: u32,
277    ) -> Result<rtp::Packet, FlexFecEncodeError> {
278        if sources.is_empty() {
279            return Err(FlexFecEncodeError::NothingToProtect);
280        }
281
282        // Group by stream, in order of first appearance.
283        let mut streams: Vec<(u32, Vec<u16>)> = Vec::new();
284        let mut parity = Parity::default();
285        for packet in sources {
286            let sequence_number = packet.header.sequence_number;
287            match streams
288                .iter_mut()
289                .find(|(ssrc, _)| *ssrc == packet.header.ssrc)
290            {
291                Some((_, sequence_numbers)) => {
292                    if sequence_numbers.contains(&sequence_number) {
293                        return Err(FlexFecEncodeError::DuplicateSequenceNumber);
294                    }
295                    sequence_numbers.push(sequence_number);
296                }
297                None => {
298                    if streams.len() == FLEXFEC_MAX_PROTECTED_SSRCS {
299                        return Err(FlexFecEncodeError::TooManySsrcs);
300                    }
301                    streams.push((packet.header.ssrc, vec![sequence_number]));
302                }
303            }
304            parity.add(&wire_of(packet)?);
305        }
306
307        let mut payload =
308            Vec::with_capacity(FLEXFEC_RECOVERY_SIZE + streams.len() * 16 + parity.payload.len());
309        // The version bits of the XOR are skipped; R and F take their place (section 6.2).
310        parity.recovery[0] = (parity.recovery[0] & 0x3F)
311            | repair_variant_bits(matches!(layout, FlexFecLayout::Fixed { .. }));
312        payload.extend_from_slice(&parity.recovery);
313
314        for (_, sequence_numbers) in &streams {
315            // SN base: the lowest sequence number of this stream the packet protects.
316            let sn_base = lowest_sequence_number(sequence_numbers);
317            let mut offsets: Vec<u16> = sequence_numbers
318                .iter()
319                .map(|sequence_number| sequence_number.wrapping_sub(sn_base))
320                .collect();
321            offsets.sort_unstable();
322
323            match layout {
324                FlexFecLayout::Mask => {
325                    let mut mask = BitArray::new();
326                    for &offset in &offsets {
327                        if u32::from(offset) >= FLEXFEC_MAX_MASK_BITS {
328                            return Err(FlexFecEncodeError::MaskTooNarrow);
329                        }
330                        mask.set_bit(u32::from(offset));
331                    }
332                    write_mask_block(&mut payload, sn_base, &mask);
333                }
334                FlexFecLayout::Fixed { l, d } => {
335                    let expected: Vec<u16> = if l == 0 {
336                        // L=0 D=0 is reserved and MUST NOT be sent (section 4.2.2.2).
337                        return Err(FlexFecEncodeError::NotTheFixedBlock);
338                    } else if d <= 1 {
339                        (0..u16::from(l)).collect()
340                    } else {
341                        (0..u16::from(d)).map(|row| row * u16::from(l)).collect()
342                    };
343                    if offsets != expected {
344                        return Err(FlexFecEncodeError::NotTheFixedBlock);
345                    }
346                    write_fixed_block(&mut payload, sn_base, l, d);
347                }
348            }
349        }
350        payload.extend_from_slice(&parity.payload);
351
352        let csrc = streams.iter().map(|(ssrc, _)| *ssrc).collect();
353        Ok(self.repair_packet(csrc, timestamp, payload))
354    }
355
356    /// Protect one block of **consecutive** packets of one stream with `protection`, returning
357    /// its repair packets in sending order (for 2-D, rows first, then columns: section
358    /// 4.2.2.2).
359    ///
360    /// Returns nothing when `block` is not exactly [`FlexFecProtection::block_len`] consecutive
361    /// packets of one stream: L and D describe positions from one base sequence number, so a
362    /// gap would protect the wrong packets.
363    pub fn encode_block(
364        &mut self,
365        protection: FlexFecProtection,
366        block: &[rtp::Packet],
367        timestamp: u32,
368    ) -> Vec<rtp::Packet> {
369        let block_len = protection.block_len();
370        if block_len == 0 || block.len() != block_len {
371            return Vec::new();
372        }
373        let consecutive = block.windows(2).all(|pair| {
374            pair[1].header.ssrc == pair[0].header.ssrc
375                && pair[1].header.sequence_number == pair[0].header.sequence_number.wrapping_add(1)
376        });
377        if !consecutive {
378            return Vec::new();
379        }
380
381        // Each entry: the layout of one repair packet and the block positions it protects.
382        let mut plan: Vec<(FlexFecLayout, Vec<usize>)> = Vec::new();
383        let rows = |plan: &mut Vec<(FlexFecLayout, Vec<usize>)>, l: u8, d_field: u8| {
384            let l = usize::from(l);
385            for row in 0..block_len / l {
386                plan.push((
387                    FlexFecLayout::Fixed {
388                        l: l as u8,
389                        d: d_field,
390                    },
391                    (row * l..(row + 1) * l).collect(),
392                ));
393            }
394        };
395        let columns = |plan: &mut Vec<(FlexFecLayout, Vec<usize>)>, l: u8, d: u8| {
396            for column in 0..usize::from(l) {
397                plan.push((
398                    FlexFecLayout::Fixed { l, d },
399                    (0..usize::from(d))
400                        .map(|row| column + row * usize::from(l))
401                        .collect(),
402                ));
403            }
404        };
405        match protection {
406            FlexFecProtection::Mask {
407                media_packets,
408                fec_packets,
409            } => {
410                let Some(coverage) = ProtectionCoverage::new(media_packets, fec_packets) else {
411                    return Vec::new();
412                };
413                for fec_index in 0..coverage.num_fec_packets() {
414                    let covered = coverage.covered_by(fec_index);
415                    if !covered.is_empty() {
416                        plan.push((
417                            FlexFecLayout::Mask,
418                            covered.into_iter().map(|index| index as usize).collect(),
419                        ));
420                    }
421                }
422            }
423            // D=0: row FEC, and no column FEC will follow.
424            FlexFecProtection::Row { l } => rows(&mut plan, l, 0),
425            FlexFecProtection::Column { l, d } => columns(&mut plan, l, d),
426            FlexFecProtection::RowAndColumn { l, d } => {
427                // D=1: row FEC, and column FEC will follow.
428                rows(&mut plan, l, 1);
429                columns(&mut plan, l, d);
430            }
431        }
432
433        let mut repair = Vec::with_capacity(plan.len());
434        for (layout, positions) in plan {
435            let sources: Vec<rtp::Packet> = positions
436                .into_iter()
437                .map(|position| block[position].clone())
438                .collect();
439            if let Ok(packet) = self.encode(layout, &sources, timestamp) {
440                repair.push(packet);
441            }
442        }
443        repair
444    }
445
446    /// Retransmit `source` on the repair stream (R=1, F=0; section 4.2.2.3): a new RTP header
447    /// prepended to the source packet, whose version bits become R and F.
448    pub fn retransmit(
449        &mut self,
450        source: &rtp::Packet,
451        timestamp: u32,
452    ) -> Result<rtp::Packet, FlexFecEncodeError> {
453        // Version 2 is binary 10, which is R=1 F=0: the FEC header of a retransmission is the
454        // source packet as it was sent.
455        let payload = wire_of(source)?;
456        Ok(self.repair_packet(Vec::new(), timestamp, payload))
457    }
458}
459
460#[cfg(test)]
461mod tests {
462    use super::*;
463    use crate::flexfec::rfc8627::header::{FlexFecHeader, FlexFecProtected};
464
465    const MEDIA_SSRC: u32 = 0x0102_0304;
466    const REPAIR_SSRC: u32 = 0x0A0B_0C0D;
467    const REPAIR_PT: u8 = 98;
468
469    fn source(ssrc: u32, sequence_number: u16, payload: &[u8]) -> rtp::Packet {
470        rtp::Packet {
471            header: rtp::header::Header {
472                version: 2,
473                marker: true,
474                payload_type: 96,
475                sequence_number,
476                timestamp: 0x1000_0000 + u32::from(sequence_number),
477                ssrc,
478                ..Default::default()
479            },
480            payload: payload.to_vec().into(),
481        }
482    }
483
484    fn run(first: u16, count: u16) -> Vec<rtp::Packet> {
485        (0..count)
486            .map(|offset| {
487                source(
488                    MEDIA_SSRC,
489                    first.wrapping_add(offset),
490                    &[offset as u8, 2, 3],
491                )
492            })
493            .collect()
494    }
495
496    fn encoder() -> FlexFecEncoder {
497        FlexFecEncoder::new(REPAIR_PT, REPAIR_SSRC)
498    }
499
500    fn blocks_of(packet: &rtp::Packet) -> Vec<(u32, Vec<u16>)> {
501        match FlexFecHeader::parse(&packet.header.csrc, &packet.payload).expect("parses") {
502            FlexFecHeader::Repair { blocks, .. } => blocks
503                .iter()
504                .map(|block| (block.ssrc, block.sequence_numbers()))
505                .collect(),
506            FlexFecHeader::Retransmission => panic!("a parity packet"),
507        }
508    }
509
510    /// Sections 4.2.1, 4.2.2.1 and 6.2, byte for byte: the repair packet for two known source
511    /// packets, computed here by hand.
512    #[test]
513    fn a_flexible_mask_repair_packet_is_laid_out_as_figure_12() {
514        // Source 1: V=2, M=1, PT=96, SN=10, TS=0x00000100, payload AA BB CC.
515        let first = rtp::Packet {
516            header: rtp::header::Header {
517                version: 2,
518                marker: true,
519                payload_type: 96,
520                sequence_number: 10,
521                timestamp: 0x0000_0100,
522                ssrc: MEDIA_SSRC,
523                ..Default::default()
524            },
525            payload: vec![0xAA, 0xBB, 0xCC].into(),
526        };
527        // Source 2: V=2, M=0, PT=97, SN=12, TS=0x00000301, payload 11 22 33 44 55.
528        let second = rtp::Packet {
529            header: rtp::header::Header {
530                version: 2,
531                marker: false,
532                payload_type: 97,
533                sequence_number: 12,
534                timestamp: 0x0000_0301,
535                ssrc: MEDIA_SSRC,
536                ..Default::default()
537            },
538            payload: vec![0x11, 0x22, 0x33, 0x44, 0x55].into(),
539        };
540
541        let repair = encoder()
542            .with_base_sequence_number(500)
543            .encode(FlexFecLayout::Mask, &[first, second], 0xCAFE_F00D)
544            .expect("encodes");
545
546        let mut wire = vec![0u8; repair.marshal_size()];
547        repair.marshal_to(&mut wire).expect("marshal");
548        assert_eq!(
549            vec![
550                // RTP header: V=2, CC=1; M=0, PT=98; SN=500; TS; repair SSRC; CSRC = source SSRC.
551                0x81,
552                98,
553                0x01,
554                0xF4,
555                0xCA,
556                0xFE,
557                0xF0,
558                0x0D,
559                0x0A,
560                0x0B,
561                0x0C,
562                0x0D,
563                0x01,
564                0x02,
565                0x03,
566                0x04,
567                // R=0 F=0, P/X/CC recovery 0; M recovery 1 ^ 0, PT recovery 96 ^ 97 = 1.
568                0x00,
569                0x81,
570                // length recovery: 3 ^ 5.
571                0x00,
572                0x06,
573                // TS recovery: 0x100 ^ 0x301.
574                0x00,
575                0x00,
576                0x02,
577                0x01,
578                // SN base 10; k=0, mask bits 0 and 2.
579                0x00,
580                0x0A,
581                0b0101_0000,
582                0x00,
583                // Repair payload: AA BB CC 00 00 ^ 11 22 33 44 55.
584                0xBB,
585                0x99,
586                0xFF,
587                0x44,
588                0x55,
589            ],
590            wire
591        );
592    }
593
594    /// Section 4.2.1: the marker is 0, the sequence number is one higher each packet, and the
595    /// timestamp is what the caller's send clock says.
596    #[test]
597    fn repair_packets_form_their_own_stream() {
598        let mut encoder = encoder().with_base_sequence_number(65_535);
599        let first = encoder
600            .encode(FlexFecLayout::Mask, &run(1, 3), 111)
601            .expect("encodes");
602        let second = encoder
603            .encode(FlexFecLayout::Mask, &run(4, 3), 222)
604            .expect("encodes");
605
606        for packet in [&first, &second] {
607            assert_eq!(2, packet.header.version);
608            assert!(!packet.header.marker, "marker SHALL be 0");
609            assert!(!packet.header.padding && !packet.header.extension);
610            assert_eq!(REPAIR_PT, packet.header.payload_type);
611            assert_eq!(REPAIR_SSRC, packet.header.ssrc);
612            assert_eq!(vec![MEDIA_SSRC], packet.header.csrc, "the protected stream");
613        }
614        assert_eq!(65_535, first.header.sequence_number);
615        assert_eq!(
616            0, second.header.sequence_number,
617            "one higher, across the wrap"
618        );
619        assert_eq!(
620            (111, 222),
621            (first.header.timestamp, second.header.timestamp)
622        );
623    }
624
625    /// Section 4.2.2.1: SN base is the lowest sequence number protected, taking wrap-around
626    /// into account, whatever order the packets were handed over in.
627    #[test]
628    fn sn_base_is_the_lowest_protected_sequence_number_across_the_wrap() {
629        let sources = vec![
630            source(MEDIA_SSRC, 2, &[1]),
631            source(MEDIA_SSRC, 65_534, &[2]),
632            source(MEDIA_SSRC, 0, &[3]),
633        ];
634        let repair = encoder()
635            .encode(FlexFecLayout::Mask, &sources, 0)
636            .expect("encodes");
637
638        assert_eq!(
639            vec![(MEDIA_SSRC, vec![65_534, 0, 2])],
640            blocks_of(&repair),
641            "base 65534, bits 0, 2 and 4"
642        );
643        assert_eq!([0xFF, 0xFE], repair.payload[8..10]);
644    }
645
646    /// Section 4.2.2.1: one SN base and mask block per protected stream, the streams named in
647    /// the CSRC list in the same order.
648    #[test]
649    fn several_streams_get_a_csrc_and_a_block_each() {
650        let sources = vec![
651            source(0x11, 100, &[1]),
652            source(0x22, 7000, &[2, 2]),
653            source(0x11, 101, &[3]),
654            source(0x22, 7050, &[4, 4, 4]),
655        ];
656        let repair = encoder()
657            .encode(FlexFecLayout::Mask, &sources, 0)
658            .expect("encodes");
659
660        assert_eq!(vec![0x11, 0x22], repair.header.csrc);
661        assert_eq!(
662            vec![(0x11, vec![100, 101]), (0x22, vec![7000, 7050])],
663            blocks_of(&repair)
664        );
665        // 8 recovery octets, a 4-octet block, a 16-octet block (bit 50 needs the third mask),
666        // then a payload as long as the longest source.
667        assert_eq!(8 + 4 + 16 + 3, repair.payload.len());
668    }
669
670    #[test]
671    fn the_mask_grows_only_as_far_as_the_highest_packet_needs() {
672        let length = |last: u16| {
673            let sources = vec![source(MEDIA_SSRC, 0, &[]), source(MEDIA_SSRC, last, &[])];
674            encoder()
675                .encode(FlexFecLayout::Mask, &sources, 0)
676                .expect("encodes")
677                .payload
678                .len()
679        };
680        assert_eq!(12, length(14), "15-bit mask");
681        assert_eq!(16, length(15), "46-bit mask");
682        assert_eq!(16, length(45));
683        assert_eq!(24, length(46), "110-bit mask");
684        assert_eq!(24, length(109));
685    }
686
687    #[test]
688    fn what_no_header_can_name_is_refused() {
689        let mut encoder = encoder();
690        assert_eq!(
691            Err(FlexFecEncodeError::NothingToProtect),
692            encoder.encode(FlexFecLayout::Mask, &[], 0)
693        );
694        assert_eq!(
695            Err(FlexFecEncodeError::MaskTooNarrow),
696            encoder.encode(
697                FlexFecLayout::Mask,
698                &[source(1, 0, &[]), source(1, 110, &[])],
699                0
700            ),
701            "the 111th sequence number"
702        );
703        assert_eq!(
704            Err(FlexFecEncodeError::DuplicateSequenceNumber),
705            encoder.encode(
706                FlexFecLayout::Mask,
707                &[source(1, 5, &[]), source(1, 5, &[])],
708                0
709            )
710        );
711        let sixteen: Vec<rtp::Packet> = (0..16).map(|ssrc| source(ssrc, 1, &[])).collect();
712        assert_eq!(
713            Err(FlexFecEncodeError::TooManySsrcs),
714            encoder.encode(FlexFecLayout::Mask, &sixteen, 0)
715        );
716        let mut version_1 = source(1, 1, &[]);
717        version_1.header.version = 1;
718        assert_eq!(
719            Err(FlexFecEncodeError::NotVersion2),
720            encoder.encode(FlexFecLayout::Mask, &[version_1], 0)
721        );
722        assert_eq!(
723            0,
724            encoder.next_sequence_number(),
725            "a refused packet uses no sequence number"
726        );
727    }
728
729    /// Section 4.2.2.2: L=0 D=0 MUST NOT be sent, and L/D must describe the packets protected.
730    #[test]
731    fn a_fixed_layout_that_does_not_describe_the_packets_is_refused() {
732        let mut encoder = encoder();
733        for (l, d) in [(0u8, 0u8), (0, 3)] {
734            assert_eq!(
735                Err(FlexFecEncodeError::NotTheFixedBlock),
736                encoder.encode(FlexFecLayout::Fixed { l, d }, &run(1, 4), 0),
737                "L={l} D={d}"
738            );
739        }
740        assert_eq!(
741            Err(FlexFecEncodeError::NotTheFixedBlock),
742            encoder.encode(FlexFecLayout::Fixed { l: 4, d: 0 }, &run(1, 3), 0),
743            "three packets are not a row of four"
744        );
745        assert_eq!(
746            Err(FlexFecEncodeError::NotTheFixedBlock),
747            encoder.encode(FlexFecLayout::Fixed { l: 4, d: 3 }, &run(1, 3), 0),
748            "three consecutive packets are not a column"
749        );
750        assert!(
751            encoder
752                .encode(FlexFecLayout::Fixed { l: 4, d: 1 }, &run(1, 4), 0)
753                .is_ok()
754        );
755    }
756
757    fn fixed_fields(packet: &rtp::Packet) -> (u16, u8, u8) {
758        assert_eq!(0x40, packet.payload[0] & 0xC0, "R=0 F=1");
759        (
760            u16::from_be_bytes([packet.payload[8], packet.payload[9]]),
761            packet.payload[10],
762            packet.payload[11],
763        )
764    }
765
766    /// Section 1.1.1 (Figure 2) and Figure 14: row FEC over L consecutive packets, sent with
767    /// D=0 because no column FEC follows.
768    #[test]
769    fn row_protection_sends_one_repair_packet_per_row_with_d_zero() {
770        let repair = encoder().encode_block(FlexFecProtection::Row { l: 4 }, &run(100, 4), 0);
771
772        assert_eq!(1, repair.len());
773        assert_eq!((100, 4, 0), fixed_fields(&repair[0]));
774        assert_eq!(
775            vec![(MEDIA_SSRC, vec![100, 101, 102, 103])],
776            blocks_of(&repair[0])
777        );
778    }
779
780    /// Section 1.1.2 (Figure 5): column FEC, one repair packet per column of an L by D block,
781    /// each over D packets L apart, its SN base the column's first packet.
782    #[test]
783    fn column_protection_sends_one_repair_packet_per_column() {
784        let repair =
785            encoder().encode_block(FlexFecProtection::Column { l: 4, d: 3 }, &run(1, 12), 0);
786
787        assert_eq!(4, repair.len());
788        assert_eq!(
789            vec![(1, 4, 3), (2, 4, 3), (3, 4, 3), (4, 4, 3)],
790            repair.iter().map(fixed_fields).collect::<Vec<_>>()
791        );
792        assert_eq!(vec![(MEDIA_SSRC, vec![1, 5, 9])], blocks_of(&repair[0]));
793        assert_eq!(vec![(MEDIA_SSRC, vec![4, 8, 12])], blocks_of(&repair[3]));
794    }
795
796    /// Section 1.1.4 (Figure 7) and Figure 14: 2-D FEC sends the row packets with D=1 ("column
797    /// FEC will follow"), then the column packets.
798    #[test]
799    fn two_dimensional_protection_sends_rows_with_d_one_then_columns() {
800        let repair = encoder().encode_block(
801            FlexFecProtection::RowAndColumn { l: 4, d: 3 },
802            &run(1, 12),
803            0,
804        );
805
806        assert_eq!(
807            vec![
808                (1, 4, 1),
809                (5, 4, 1),
810                (9, 4, 1),
811                (1, 4, 3),
812                (2, 4, 3),
813                (3, 4, 3),
814                (4, 4, 3)
815            ],
816            repair.iter().map(fixed_fields).collect::<Vec<_>>()
817        );
818        for (offset, packet) in repair.iter().enumerate() {
819            assert_eq!(offset as u16, packet.header.sequence_number);
820        }
821    }
822
823    /// The flexible-mask shape interleaves, as the draft-03 coder does, and every repair
824    /// packet's SN base is its own lowest packet.
825    #[test]
826    fn mask_protection_interleaves_with_a_base_per_repair_packet() {
827        let repair = encoder().encode_block(
828            FlexFecProtection::Mask {
829                media_packets: 6,
830                fec_packets: 2,
831            },
832            &run(100, 6),
833            0,
834        );
835
836        assert_eq!(2, repair.len());
837        assert_eq!(
838            vec![(MEDIA_SSRC, vec![100, 102, 104])],
839            blocks_of(&repair[0])
840        );
841        assert_eq!(
842            vec![(MEDIA_SSRC, vec![101, 103, 105])],
843            blocks_of(&repair[1])
844        );
845        for packet in &repair {
846            assert_eq!(0, packet.payload[0] & 0xC0, "R=0 F=0");
847            let FlexFecHeader::Repair { blocks, .. } =
848                FlexFecHeader::parse(&packet.header.csrc, &packet.payload).expect("parses")
849            else {
850                panic!("a parity packet");
851            };
852            assert!(matches!(blocks[0].protected, FlexFecProtected::Mask(_)));
853        }
854    }
855
856    /// A mask reaches 110 packets, one more than draft-03's.
857    #[test]
858    fn a_mask_block_of_110_packets_is_fully_named() {
859        let repair = encoder().encode_block(
860            FlexFecProtection::Mask {
861                media_packets: 110,
862                fec_packets: 1,
863            },
864            &run(65_500, 110),
865            0,
866        );
867        assert_eq!(1, repair.len());
868        let named = &blocks_of(&repair[0])[0].1;
869        assert_eq!(110, named.len());
870        assert_eq!(65_500u16.wrapping_add(109), named[109]);
871    }
872
873    #[test]
874    fn a_block_that_is_not_the_shape_asked_for_yields_nothing() {
875        let mut encoder = encoder();
876        let column = FlexFecProtection::Column { l: 4, d: 3 };
877
878        assert!(encoder.encode_block(column, &run(1, 11), 0).is_empty());
879        let mut gapped = run(1, 12);
880        gapped[7].header.sequence_number = 99;
881        assert!(encoder.encode_block(column, &gapped, 0).is_empty());
882        let mut other_stream = run(1, 12);
883        other_stream[11].header.ssrc = 5;
884        assert!(encoder.encode_block(column, &other_stream, 0).is_empty());
885
886        for unusable in [
887            FlexFecProtection::Row { l: 0 },
888            FlexFecProtection::Column { l: 0, d: 3 },
889            FlexFecProtection::Column { l: 4, d: 1 },
890            FlexFecProtection::RowAndColumn { l: 4, d: 0 },
891            FlexFecProtection::Mask {
892                media_packets: 111,
893                fec_packets: 1,
894            },
895            FlexFecProtection::Mask {
896                media_packets: 5,
897                fec_packets: 0,
898            },
899        ] {
900            assert_eq!(0, unusable.block_len(), "{unusable:?}");
901            assert_eq!(0, unusable.repair_packets_per_block(), "{unusable:?}");
902        }
903        assert_eq!(0, encoder.next_sequence_number());
904    }
905
906    /// Section 4.2.2.3, Figure 15: the retransmission payload is the source packet, RTP header
907    /// first, and its first two bits read R=1 F=0. The source SSRC is in that header, not in
908    /// the CSRC list.
909    #[test]
910    fn a_retransmission_is_the_source_packet_behind_a_new_rtp_header() {
911        let mut lost = source(MEDIA_SSRC, 4321, &[9, 8, 7]);
912        lost.header.csrc = vec![0xEEEE_0001];
913        let mut wire = vec![0u8; lost.marshal_size()];
914        lost.marshal_to(&mut wire).expect("marshal");
915
916        let packet = encoder()
917            .with_base_sequence_number(77)
918            .retransmit(&lost, 9000)
919            .expect("retransmits");
920
921        assert_eq!(wire.as_slice(), &packet.payload[..]);
922        assert_eq!(0x80, packet.payload[0] & 0xC0, "R=1 F=0");
923        assert_eq!(MEDIA_SSRC.to_be_bytes(), packet.payload[8..12]);
924        assert!(packet.header.csrc.is_empty());
925        assert_eq!(
926            (REPAIR_SSRC, REPAIR_PT, 77, 9000, false),
927            (
928                packet.header.ssrc,
929                packet.header.payload_type,
930                packet.header.sequence_number,
931                packet.header.timestamp,
932                packet.header.marker
933            )
934        );
935        assert_eq!(
936            Ok(FlexFecHeader::Retransmission),
937            FlexFecHeader::parse(&packet.header.csrc, &packet.payload)
938        );
939    }
940}