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