Skip to main content

rtci_interceptor/flexfec/draft03/
encoder.rs

1//! FlexFEC draft-03 repair packet construction.
2
3use crate::flexfec::bit_array::BitArray;
4use crate::flexfec::coverage::ProtectionCoverage;
5use shared::marshal::{Marshal, MarshalSize};
6
7/// Bytes of RTP header a repair packet recovers from, and the offset its payload starts at.
8pub(crate) const BASE_RTP_HEADER_SIZE: usize = 12;
9
10/// The fixed part of a draft-03 repair payload: recovery fields, SSRC count, the protected SSRC,
11/// the base sequence number and the first packet mask.
12pub(crate) const BASE_HEADER_SIZE: usize = 20;
13
14/// Bytes added when the second packet mask is present.
15const MASK2_SIZE: usize = 4;
16
17/// Bytes added when the third packet mask is present.
18const MASK3_SIZE: usize = 8;
19
20/// The most media packets one draft-03 repair packet can describe: 15 + 31 + 63 mask bits
21/// (draft-ietf-payload-flexible-fec-scheme-03, section 4.2).
22///
23/// One fewer than RFC 8627's 110: draft-03 spends the first bit of the third mask word on a
24/// k-bit, the RFC does not.
25pub const DRAFT03_MAX_MEDIA_PACKETS: u32 = 109;
26
27/// The largest repair packet (RTP header, FlexFEC header and repair payload) a draft-03 encoder
28/// builds by default: what an Ethernet path MTU of 1500 octets leaves for an RTP packet under
29/// IPv6 (40), UDP (8) and the longest SRTP authentication tag of the DTLS-SRTP profiles (16).
30///
31/// draft-ietf-payload-flexible-fec-scheme-03 section 6.2: a repair packet is the largest
32/// packet it protects plus 20 to 32 octets, "which may cause problems if the resulting repair
33/// packet size exceeds the Maximum Transmission Unit size of the path": a repair packet that
34/// would be larger is not built, and the block goes unprotected by it.
35pub const DRAFT03_MAX_REPAIR_PACKET_SIZE: usize = 1436;
36
37/// Builds FlexFEC **draft-03** repair packets.
38///
39/// Draft-03 rather than [RFC 8627] because draft-03 is what browsers negotiate as
40/// `video/flexfec-03`. The RFC states its payload formats are not backward compatible with the
41/// earlier drafts, so the two are separate implementations with separate vectors — a draft-03
42/// round trip is evidence about browsers, not about the RFC.
43///
44/// ```text
45///  0                   1                   2                   3
46///  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
47/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
48/// |0|0| P|X|  CC  |M| PT recovery |         length recovery       |
49/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
50/// |                          TS recovery                          |
51/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
52/// |   SSRCCount   |                    reserved                   |
53/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
54/// |                             SSRC_i                            |
55/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
56/// |           SN base_i           |k|          Mask [0-14]        |
57/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
58/// |k|                   Mask [15-45] (optional)                   |
59/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
60/// |k|                                                             |
61/// +-+                   Mask [46-108] (optional)                  |
62/// |                                                               |
63/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
64/// ```
65///
66/// [RFC 8627]: https://www.rfc-editor.org/rfc/rfc8627
67#[derive(Debug)]
68pub struct FlexFec03Encoder {
69    payload_type: u8,
70    ssrc: u32,
71    next_sequence_number: u16,
72    coverage: Option<ProtectionCoverage>,
73    max_packet_size: usize,
74}
75
76impl FlexFec03Encoder {
77    /// A repair-stream encoder sending `payload_type` on `ssrc`.
78    ///
79    /// The repair stream has its own SSRC and its own sequence-number space, both negotiated
80    /// separately from the media it protects.
81    pub fn new(payload_type: u8, ssrc: u32) -> Self {
82        Self {
83            payload_type,
84            ssrc,
85            next_sequence_number: 0,
86            coverage: None,
87            max_packet_size: DRAFT03_MAX_REPAIR_PACKET_SIZE,
88        }
89    }
90
91    /// The largest repair packet to build, in octets (RTP header included): one that would be
92    /// larger is left out (section 6.2). [`DRAFT03_MAX_REPAIR_PACKET_SIZE`] by default.
93    pub fn with_max_packet_size(mut self, max_packet_size: usize) -> Self {
94        self.max_packet_size = max_packet_size;
95        self
96    }
97
98    /// Start the repair stream's sequence numbers at `sequence_number`.
99    pub fn with_base_sequence_number(mut self, sequence_number: u16) -> Self {
100        self.next_sequence_number = sequence_number;
101        self
102    }
103
104    /// The sequence number the next repair packet will carry.
105    pub fn next_sequence_number(&self) -> u16 {
106        self.next_sequence_number
107    }
108
109    /// Build up to `num_fec_packets` repair packets protecting `media_packets`, stamped with
110    /// `timestamp`.
111    ///
112    /// `timestamp` is the repair stream's RTP timestamp for the instant these packets are sent
113    /// (draft-03 section 4.2: "the timestamp SHALL be set to a time corresponding to the repair
114    /// packet's transmission time"). It is the caller's send clock, not the media's: the repair
115    /// stream is an RTP stream of its own, and a receiver computes its jitter from this field.
116    ///
117    /// Returns nothing when the media packets are not a **consecutive** run: a packet mask
118    /// describes positions relative to one base sequence number, so a gap would silently shift
119    /// every position after it and protect the wrong packets. A caller that has lost a packet
120    /// should start a new block rather than encode across the hole. Returns nothing, too, for a
121    /// block of more than [`DRAFT03_MAX_MEDIA_PACKETS`] packets: the caller must split it.
122    pub fn encode(
123        &mut self,
124        media_packets: &[rtp::Packet],
125        num_fec_packets: u32,
126        timestamp: u32,
127    ) -> Vec<rtp::Packet> {
128        if media_packets.is_empty() || num_fec_packets == 0 {
129            return Vec::new();
130        }
131        // The coverage can describe 110 positions (RFC 8627's masks); draft-03's wire masks
132        // hold 109. A 110th packet would be XORed into the repair data without being named in
133        // the mask, and every recovery from that repair packet would be corrupt.
134        if media_packets.len() as u32 > DRAFT03_MAX_MEDIA_PACKETS {
135            return Vec::new();
136        }
137
138        let consecutive = media_packets.windows(2).all(|pair| {
139            pair[1].header.sequence_number == pair[0].header.sequence_number.wrapping_add(1)
140        });
141        if !consecutive {
142            return Vec::new();
143        }
144
145        let num_media_packets = media_packets.len() as u32;
146        match &mut self.coverage {
147            Some(coverage) => coverage.update(num_media_packets, num_fec_packets),
148            None => match ProtectionCoverage::new(num_media_packets, num_fec_packets) {
149                Some(coverage) => self.coverage = Some(coverage),
150                None => return Vec::new(),
151            },
152        }
153        let Some(coverage) = &self.coverage else {
154            return Vec::new();
155        };
156        if coverage.num_media_packets() != num_media_packets {
157            // The block is longer than the masks can describe; the caller must split it.
158            return Vec::new();
159        }
160
161        let num_fec_packets = coverage.num_fec_packets();
162        let base_sequence_number = media_packets[0].header.sequence_number;
163        let mut repair_packets = Vec::with_capacity(num_fec_packets as usize);
164        for fec_index in 0..num_fec_packets {
165            if let Some(packet) =
166                self.encode_one(fec_index, base_sequence_number, media_packets, timestamp)
167            {
168                repair_packets.push(packet);
169            }
170        }
171        repair_packets
172    }
173
174    fn encode_one(
175        &mut self,
176        fec_index: u32,
177        base_sequence_number: u16,
178        media_packets: &[rtp::Packet],
179        timestamp: u32,
180    ) -> Option<rtp::Packet> {
181        let coverage = self.coverage.as_ref()?;
182        let covered = coverage.covered_by(fec_index);
183        // A repair packet protecting nothing carries no information.
184        let first_covered = *covered.first()?;
185
186        // SN base is the lowest sequence number *this* repair packet protects (section 4.2), not
187        // the block's: the mask is written relative to it, so the second repair packet of an
188        // interleaved block starts its mask at bit 0 too and stays in the short mask longer.
189        let base_sequence_number = base_sequence_number.wrapping_add(first_covered as u16);
190        let mut mask = BitArray::new();
191        for &index in &covered {
192            mask.set_bit(index - first_covered);
193        }
194
195        let mask2 = mask.mask2();
196        let mask3 = mask.mask3_draft03();
197        let header_size = BASE_HEADER_SIZE
198            + if mask2 != 0 || mask3 != 0 {
199                MASK2_SIZE
200            } else {
201                0
202            }
203            + if mask3 != 0 { MASK3_SIZE } else { 0 };
204
205        // The repair payload must be long enough for the largest packet it protects: recovering a
206        // lost packet means XORing this back out, so anything shorter would truncate it.
207        let max_payload = covered
208            .iter()
209            .map(|&index| media_packets[index as usize].marshal_size() - BASE_RTP_HEADER_SIZE)
210            .max()?;
211
212        // Section 6.2: not larger than the path MTU allows. Checked before anything is built,
213        // and before a sequence number is taken, so the repair stream has no hole for it.
214        if BASE_RTP_HEADER_SIZE + header_size + max_payload > self.max_packet_size {
215            return None;
216        }
217
218        let mut payload = vec![0u8; header_size + max_payload];
219        let (header, repair) = payload.split_at_mut(header_size);
220
221        let mut protected_ssrc = None;
222        for &index in &covered {
223            let media_packet = &media_packets[index as usize];
224            let size = media_packet.marshal_size();
225            let mut buffer = vec![0u8; size];
226            media_packet.marshal_to(&mut buffer).ok()?;
227
228            protected_ssrc.get_or_insert(media_packet.header.ssrc);
229
230            // Recovery fields are the XOR of the corresponding media header bytes, so a receiver
231            // holding every packet but one can XOR the rest back out and be left with it.
232            header[0] ^= buffer[0];
233            header[1] ^= buffer[1];
234            // The first two bits are the RTP version, which is not recovered — it is always 2.
235            header[0] &= 0b0011_1111;
236
237            let length_recovery = (size - BASE_RTP_HEADER_SIZE) as u16;
238            header[2] ^= (length_recovery >> 8) as u8;
239            header[3] ^= length_recovery as u8;
240
241            // Timestamp recovery. The sequence number at bytes 2..4 of the media header is *not*
242            // recovered this way — its position is taken by length recovery, and a lost packet's
243            // sequence number is implied by its position in the mask.
244            for byte in 4..8 {
245                header[byte] ^= buffer[byte];
246            }
247
248            for (target, &source) in repair.iter_mut().zip(&buffer[BASE_RTP_HEADER_SIZE..]) {
249                *target ^= source;
250            }
251        }
252
253        header[8] = 1; // SSRCCount: draft-03 protects a single stream per repair packet.
254        header[9..12].fill(0); // reserved
255        header[12..16].copy_from_slice(&protected_ssrc?.to_be_bytes());
256        header[16..18].copy_from_slice(&base_sequence_number.to_be_bytes());
257        header[18..20].copy_from_slice(&mask.mask1().to_be_bytes());
258
259        // The k-bit marks the last mask present. It is the top bit of each mask word, which is
260        // why mask1 is 15 bits rather than 16 and mask3 is 63 rather than 64.
261        if mask2 == 0 && mask3 == 0 {
262            header[18] |= 0b1000_0000;
263        } else {
264            header[20..24].copy_from_slice(&mask2.to_be_bytes());
265            if mask3 == 0 {
266                header[20] |= 0b1000_0000;
267            } else {
268                header[24..32].copy_from_slice(&mask3.to_be_bytes());
269                header[24] |= 0b1000_0000;
270            }
271        }
272
273        let sequence_number = self.next_sequence_number;
274        self.next_sequence_number = self.next_sequence_number.wrapping_add(1);
275
276        Some(rtp::Packet {
277            header: rtp::header::Header {
278                version: 2,
279                payload_type: self.payload_type,
280                sequence_number,
281                // The repair stream's own send clock (section 4.2), handed in by the caller.
282                // Upstream hardcodes a constant here.
283                timestamp,
284                ssrc: self.ssrc,
285                csrc: Vec::new(),
286                ..Default::default()
287            },
288            payload: payload.into(),
289        })
290    }
291}
292
293/// The packet mask a repair packet declares, read back off the wire.
294///
295/// Used by the tests here and by the decoder; kept beside the encoder so the two cannot drift.
296pub(crate) fn parse_packet_mask(header: &[u8]) -> Option<(BitArray, usize)> {
297    if header.len() < BASE_HEADER_SIZE {
298        return None;
299    }
300
301    let mut mask = BitArray::new();
302    let mask1 = u16::from_be_bytes([header[18] & 0b0111_1111, header[19]]);
303    for bit in 0..15 {
304        if mask1 & (1 << (14 - bit)) != 0 {
305            mask.set_bit(bit);
306        }
307    }
308    if header[18] & 0b1000_0000 != 0 {
309        return Some((mask, BASE_HEADER_SIZE));
310    }
311
312    if header.len() < BASE_HEADER_SIZE + MASK2_SIZE {
313        return None;
314    }
315    let mask2 = u32::from_be_bytes([header[20] & 0b0111_1111, header[21], header[22], header[23]]);
316    for bit in 0..31 {
317        if mask2 & (1 << (30 - bit)) != 0 {
318            mask.set_bit(15 + bit);
319        }
320    }
321    if header[20] & 0b1000_0000 != 0 {
322        return Some((mask, BASE_HEADER_SIZE + MASK2_SIZE));
323    }
324
325    if header.len() < BASE_HEADER_SIZE + MASK2_SIZE + MASK3_SIZE {
326        return None;
327    }
328    let mut mask3_bytes = [0u8; 8];
329    mask3_bytes.copy_from_slice(&header[24..32]);
330    mask3_bytes[0] &= 0b0111_1111;
331    let mask3 = u64::from_be_bytes(mask3_bytes);
332    for bit in 0..63 {
333        if mask3 & (1 << (62 - bit)) != 0 {
334            mask.set_bit(46 + bit);
335        }
336    }
337    Some((mask, BASE_HEADER_SIZE + MASK2_SIZE + MASK3_SIZE))
338}
339
340#[cfg(test)]
341mod tests {
342    use super::*;
343
344    const MEDIA_SSRC: u32 = 476_325_762;
345    const REPAIR_SSRC: u32 = 867_589_674;
346    const REPAIR_PT: u8 = 49;
347
348    fn media_packet(sequence_number: u16, payload: &[u8]) -> rtp::Packet {
349        rtp::Packet {
350            header: rtp::header::Header {
351                version: 2,
352                marker: true,
353                payload_type: 96,
354                sequence_number,
355                timestamp: 3_653_407_706,
356                ssrc: MEDIA_SSRC,
357                ..Default::default()
358            },
359            payload: payload.to_vec().into(),
360        }
361    }
362
363    fn run(count: u16) -> Vec<rtp::Packet> {
364        (0..count)
365            .map(|i| media_packet(100 + i, &[1, 2, 3, 4, 5, i as u8]))
366            .collect()
367    }
368
369    fn encoder() -> FlexFec03Encoder {
370        FlexFec03Encoder::new(REPAIR_PT, REPAIR_SSRC)
371    }
372
373    /// Section 6.2: a repair packet is the largest packet it protects plus its header, and one
374    /// larger than the path MTU allows is not built. The limit counts the RTP header; a block
375    /// of small packets is protected as before, and the sequence numbers of the repair stream
376    /// skip nothing for the packet left out.
377    #[test]
378    fn a_repair_packet_larger_than_the_path_allows_is_not_built() {
379        let large: Vec<rtp::Packet> = (0..2u16)
380            .map(|i| media_packet(100 + i, &vec![i as u8; DRAFT03_MAX_REPAIR_PACKET_SIZE - 12]))
381            .collect();
382        let mut default = encoder().with_base_sequence_number(7);
383        assert!(
384            default.encode(&large, 1, 0).is_empty(),
385            "over the default limit"
386        );
387        let repair = default.encode(&run(2), 1, 0);
388        assert_eq!(1, repair.len());
389        assert_eq!(
390            7, repair[0].header.sequence_number,
391            "no number spent on the one left out"
392        );
393        let size = repair[0].marshal_size();
394        assert!(size <= DRAFT03_MAX_REPAIR_PACKET_SIZE);
395
396        let mut tight = encoder().with_max_packet_size(size - 1);
397        assert!(
398            tight.encode(&run(2), 1, 0).is_empty(),
399            "one octet over a lower limit"
400        );
401        let mut exact = encoder().with_max_packet_size(size);
402        assert_eq!(1, exact.encode(&run(2), 1, 0).len(), "exactly at the limit");
403    }
404
405    /// The repair packet is a stream of its own: its own SSRC, payload type and sequence numbers,
406    /// which is what distinguishes FlexFEC from RED-carried schemes.
407    #[test]
408    fn repair_packets_form_their_own_stream() {
409        let mut encoder = encoder().with_base_sequence_number(1000);
410        let repair = encoder.encode(&run(4), 2, 0);
411
412        assert_eq!(2, repair.len());
413        for (offset, packet) in repair.iter().enumerate() {
414            assert_eq!(REPAIR_SSRC, packet.header.ssrc, "not the media SSRC");
415            assert_eq!(REPAIR_PT, packet.header.payload_type);
416            assert_eq!(1000 + offset as u16, packet.header.sequence_number);
417            assert_eq!(2, packet.header.version);
418        }
419        assert_eq!(1002, encoder.next_sequence_number());
420    }
421
422    /// The block is described relative to one base sequence number, so a gap would shift every
423    /// position after it and protect the wrong packets. Encoding across a hole is refused rather
424    /// than done wrongly.
425    #[test]
426    fn a_block_with_a_gap_is_refused() {
427        let mut packets = run(3);
428        packets[2].header.sequence_number = 105; // 100, 101, 105
429
430        assert!(encoder().encode(&packets, 1, 0).is_empty());
431    }
432
433    #[test]
434    fn an_out_of_order_block_is_refused() {
435        let mut packets = run(2);
436        packets.swap(0, 1);
437
438        assert!(encoder().encode(&packets, 1, 0).is_empty());
439    }
440
441    #[test]
442    fn a_block_that_wraps_the_sequence_space_is_accepted() {
443        let packets = vec![
444            media_packet(65534, &[1]),
445            media_packet(65535, &[2]),
446            media_packet(0, &[3]),
447        ];
448        assert_eq!(
449            1,
450            encoder().encode(&packets, 1, 0).len(),
451            "0 follows 65535: consecutive, not a gap"
452        );
453    }
454
455    #[test]
456    fn nothing_to_protect_produces_nothing() {
457        assert!(encoder().encode(&[], 1, 0).is_empty());
458        assert!(encoder().encode(&run(3), 0, 0).is_empty());
459    }
460
461    /// A repair packet covering no media packet carries no information, so the surplus is dropped
462    /// rather than emitted as an empty packet.
463    #[test]
464    fn surplus_repair_packets_are_not_emitted() {
465        let repair = encoder().encode(&run(2), 4, 0);
466        assert_eq!(
467            2,
468            repair.len(),
469            "two media packets can back two repair packets"
470        );
471    }
472
473    /// Draft-03's three masks hold 15 + 31 + 63 = 109 bits (section 4.2). The coverage type can
474    /// describe 110, which is RFC 8627's width: a 110-packet block XORed the last packet into the
475    /// repair data without naming it in the mask.
476    #[test]
477    fn a_block_longer_than_the_masks_can_describe_is_refused() {
478        assert!(
479            encoder()
480                .encode(&run(DRAFT03_MAX_MEDIA_PACKETS as u16 + 1), 1, 0)
481                .is_empty(),
482            "110 packets: the caller must split the block"
483        );
484
485        let repair = encoder().encode(&run(DRAFT03_MAX_MEDIA_PACKETS as u16), 1, 0);
486        assert_eq!(1, repair.len(), "109 packets fit");
487        let (mask, _) = parse_packet_mask(&repair[0].payload).expect("parses");
488        assert!(
489            (0..DRAFT03_MAX_MEDIA_PACKETS).all(|bit| mask.bit(bit)),
490            "and every one of them is named in the mask"
491        );
492    }
493
494    // ---------------------------------------------------------------------------------------
495    // Header layout
496    // ---------------------------------------------------------------------------------------
497
498    #[test]
499    fn the_header_names_the_stream_and_block_it_protects() {
500        let repair = encoder().encode(&run(4), 1, 0);
501        let payload = &repair[0].payload;
502
503        assert_eq!(1, payload[8], "SSRCCount: draft-03 protects one stream");
504        assert_eq!(&[0, 0, 0], &payload[9..12], "reserved");
505        assert_eq!(
506            MEDIA_SSRC.to_be_bytes(),
507            payload[12..16],
508            "the protected stream"
509        );
510        assert_eq!(
511            100u16.to_be_bytes(),
512            payload[16..18],
513            "the lowest sequence number it protects"
514        );
515    }
516
517    /// The k-bit marks the last mask present, which is why mask1 is 15 bits and not 16.
518    #[test]
519    fn a_short_block_carries_one_mask_with_the_k_bit_set() {
520        let repair = encoder().encode(&run(4), 1, 0);
521        let payload = &repair[0].payload;
522
523        assert_eq!(
524            BASE_HEADER_SIZE + 6,
525            payload.len(),
526            "20-byte header plus the longest protected payload"
527        );
528        assert_ne!(0, payload[18] & 0b1000_0000, "k-bit set: no further masks");
529
530        let (mask, header_size) = parse_packet_mask(payload).expect("parses");
531        assert_eq!(BASE_HEADER_SIZE, header_size);
532        assert_eq!(
533            vec![true, true, true, true],
534            (0..4).map(|bit| mask.bit(bit)).collect::<Vec<_>>(),
535            "all four media packets covered"
536        );
537    }
538
539    #[test]
540    fn a_longer_block_adds_the_second_mask() {
541        let repair = encoder().encode(&run(20), 1, 0);
542        let payload = &repair[0].payload;
543
544        assert_eq!(
545            0,
546            payload[18] & 0b1000_0000,
547            "k-bit clear: another mask follows"
548        );
549        assert_ne!(0, payload[20] & 0b1000_0000, "and that one is the last");
550
551        let (mask, header_size) = parse_packet_mask(payload).expect("parses");
552        assert_eq!(BASE_HEADER_SIZE + MASK2_SIZE, header_size);
553        for bit in 0..20 {
554            assert!(mask.bit(bit), "media packet {bit} covered");
555        }
556        assert!(!mask.bit(20), "and nothing beyond the block");
557    }
558
559    #[test]
560    fn a_block_beyond_46_packets_adds_the_third_mask() {
561        let repair = encoder().encode(&run(60), 1, 0);
562        let payload = &repair[0].payload;
563
564        assert_eq!(0, payload[18] & 0b1000_0000);
565        assert_eq!(0, payload[20] & 0b1000_0000);
566        assert_ne!(0, payload[24] & 0b1000_0000, "the third mask is the last");
567
568        let (mask, header_size) = parse_packet_mask(payload).expect("parses");
569        assert_eq!(BASE_HEADER_SIZE + MASK2_SIZE + MASK3_SIZE, header_size);
570        for bit in 0..60 {
571            assert!(mask.bit(bit), "media packet {bit} covered");
572        }
573    }
574
575    /// The mask on the wire has to name exactly the packets the coverage assigned, or a receiver
576    /// XORs the wrong set back out and "recovers" corruption.
577    #[test]
578    fn the_declared_mask_matches_the_interleaved_coverage() {
579        let repair = encoder().encode(&run(6), 2, 0);
580        assert_eq!(2, repair.len());
581
582        // Each mask is relative to its own packet's SN base, so both start at bit 0.
583        let protected = |packet: &rtp::Packet| {
584            let base = u16::from_be_bytes([packet.payload[16], packet.payload[17]]);
585            let (mask, _) = parse_packet_mask(&packet.payload).expect("parses");
586            (0..6u16)
587                .filter(|&bit| mask.bit(u32::from(bit)))
588                .map(|bit| base + bit)
589                .collect::<Vec<_>>()
590        };
591
592        assert_eq!(vec![100, 102, 104], protected(&repair[0]));
593        assert_eq!(vec![101, 103, 105], protected(&repair[1]));
594    }
595
596    /// Section 4.2: SN base is "the lowest sequence number, taking wrap around into account, of
597    /// those source packets protected by this repair packet". The second repair packet of an
598    /// interleaved block starts one packet later than the block.
599    #[test]
600    fn sn_base_is_the_lowest_sequence_number_each_repair_packet_protects() {
601        let repair = encoder().encode(&run(6), 2, 0);
602        let base =
603            |packet: &rtp::Packet| u16::from_be_bytes([packet.payload[16], packet.payload[17]]);
604
605        assert_eq!(100, base(&repair[0]));
606        assert_eq!(
607            101,
608            base(&repair[1]),
609            "its first protected packet, not the block's"
610        );
611        for packet in &repair {
612            let (mask, _) = parse_packet_mask(&packet.payload).expect("parses");
613            assert!(mask.bit(0), "so bit 0 of every mask is set");
614        }
615
616        // Across the sequence wrap the base is still the first packet in sending order.
617        let wrapping = vec![
618            media_packet(65_534, &[1]),
619            media_packet(65_535, &[2]),
620            media_packet(0, &[3]),
621            media_packet(1, &[4]),
622        ];
623        let repair = encoder().encode(&wrapping, 2, 0);
624        assert_eq!(65_534, base(&repair[0]));
625        assert_eq!(65_535, base(&repair[1]));
626    }
627
628    /// Section 4.2: the timestamp is the repair packet's transmission time, so it is whatever the
629    /// caller's send clock says, and does not follow the media timestamps.
630    #[test]
631    fn the_repair_timestamp_is_the_send_clock_not_the_media_clock() {
632        let mut encoder = encoder();
633        // Every media packet of `run` carries the same timestamp (one large frame).
634        let first = encoder.encode(&run(4), 2, 90_000);
635        let second = encoder.encode(&run(4), 2, 93_000);
636
637        assert!(first.iter().all(|packet| packet.header.timestamp == 90_000));
638        assert!(
639            second
640                .iter()
641                .all(|packet| packet.header.timestamp == 93_000)
642        );
643    }
644
645    /// Section 4.2: the marker bit of a repair packet SHALL be 0, whatever the media's is.
646    #[test]
647    fn the_marker_bit_of_a_repair_packet_is_zero() {
648        let media = run(4);
649        assert!(media.iter().all(|packet| packet.header.marker));
650
651        for packet in encoder().encode(&media, 2, 0) {
652            assert!(!packet.header.marker);
653            let mut wire = vec![0u8; packet.marshal_size()];
654            packet.marshal_to(&mut wire).expect("marshal");
655            assert_eq!(0, wire[1] & 0x80, "and it is 0 on the wire");
656        }
657    }
658
659    /// FLEXFEC03-4.2-17, a deliberate deviation from the letter of draft-03. The draft's text
660    /// says mask bit j names packet "SN base + j + 1"; libwebrtc, the only draft-03 peer there
661    /// is, sends bit j for SN base + j, and RFC 8627 section 4.2.2.1 later wrote that down. The
662    /// engine follows libwebrtc: bit 0 is SN base itself.
663    #[test]
664    fn mask_bit_j_names_sn_base_plus_j_as_libwebrtc_sends_it() {
665        let repair = encoder().encode(&run(3), 1, 0);
666        let payload = &repair[0].payload;
667
668        assert_eq!(100u16.to_be_bytes(), payload[16..18], "SN base");
669        // k = 1 (only mask), then bits 0, 1, 2 set: packets 100, 101, 102.
670        assert_eq!([0b1111_0000, 0], payload[18..20]);
671    }
672
673    // ---------------------------------------------------------------------------------------
674    // Recovery arithmetic
675    // ---------------------------------------------------------------------------------------
676
677    /// The recovery fields must be the XOR of the media bytes they stand for. Computing that XOR
678    /// here independently is what makes this a check on the encoder rather than a restatement of
679    /// it — and it is the property the decoder will rely on, before the decoder exists.
680    #[test]
681    fn recovery_fields_are_the_xor_of_the_protected_packets() {
682        let media = run(4);
683        let repair = encoder().encode(&media, 1, 0);
684        let payload = &repair[0].payload;
685
686        let mut expected = [0u8; 8];
687        let mut expected_length = 0u16;
688        for packet in &media {
689            let mut buffer = vec![0u8; packet.marshal_size()];
690            packet.marshal_to(&mut buffer).expect("marshal");
691            expected[0] ^= buffer[0];
692            expected[1] ^= buffer[1];
693            for byte in 4..8 {
694                expected[byte] ^= buffer[byte];
695            }
696            expected_length ^= (packet.marshal_size() - BASE_RTP_HEADER_SIZE) as u16;
697        }
698        expected[0] &= 0b0011_1111;
699
700        assert_eq!(expected[0], payload[0], "flags and CC recovery");
701        assert_eq!(expected[1], payload[1], "marker and payload type recovery");
702        assert_eq!(
703            expected_length.to_be_bytes(),
704            payload[2..4],
705            "length recovery"
706        );
707        assert_eq!(expected[4..8], payload[4..8], "timestamp recovery");
708    }
709
710    #[test]
711    fn the_repair_payload_is_the_xor_of_the_protected_payloads() {
712        let media = run(4);
713        let repair = encoder().encode(&media, 1, 0);
714        let header_size = parse_packet_mask(&repair[0].payload).expect("parses").1;
715        let repair_payload = &repair[0].payload[header_size..];
716
717        let mut expected = vec![0u8; media.iter().map(|p| p.payload.len()).max().unwrap()];
718        for packet in &media {
719            for (target, &source) in expected.iter_mut().zip(packet.payload.iter()) {
720                *target ^= source;
721            }
722        }
723
724        assert_eq!(expected.as_slice(), repair_payload);
725    }
726
727    /// Recovery XORs the repair payload back out, so it has to be as long as the largest packet
728    /// it protects — a shorter one would truncate whatever it recovers.
729    #[test]
730    fn the_repair_payload_is_as_long_as_the_largest_protected_packet() {
731        let media = vec![
732            media_packet(1, &[1, 2, 3]),
733            media_packet(2, &[1, 2, 3, 4, 5, 6, 7, 8]),
734            media_packet(3, &[9]),
735        ];
736        let repair = encoder().encode(&media, 1, 0);
737        let header_size = parse_packet_mask(&repair[0].payload).expect("parses").1;
738
739        assert_eq!(8, repair[0].payload.len() - header_size);
740    }
741
742    /// The RTP version is fixed at 2 and never recovered, so the top two bits of the first
743    /// recovery byte are cleared rather than carrying XORed version bits.
744    #[test]
745    fn the_version_bits_are_not_recovered() {
746        let repair = encoder().encode(&run(3), 1, 0);
747        assert_eq!(
748            0,
749            repair[0].payload[0] & 0b1100_0000,
750            "the two version bits are zeroed"
751        );
752    }
753}