Skip to main content

rtci_interceptor/ulpfec/
encoder.rs

1//! The protection operation (RFC 5109 section 8) and the FEC packets of a separate stream (7.2).
2
3use super::UlpfecError;
4use super::header::{LONG_MASK_BITS, SHORT_MASK_BITS, UlpfecLevel, UlpfecPacket};
5use bytes::Bytes;
6use shared::marshal::Marshal;
7use std::collections::HashMap;
8use std::time::Instant;
9
10/// Octets of the fixed RTP header, which the FEC header protects; level payloads start after it.
11pub(crate) const RTP_FIXED_HEADER: usize = 12;
12
13/// One protection level to generate: how many octets it covers and which packets it protects.
14#[derive(Debug, Clone, PartialEq, Eq)]
15pub struct ProtectionLevel {
16    /// The level's protection length `Ln`, in octets.
17    pub protection_length: u16,
18    /// Sequence numbers of the media packets protected at this level.
19    pub sequence_numbers: Vec<u16>,
20}
21
22impl ProtectionLevel {
23    /// A level of `protection_length` octets over `sequence_numbers`.
24    pub fn new(protection_length: u16, sequence_numbers: impl Into<Vec<u16>>) -> Self {
25        Self {
26            protection_length,
27            sequence_numbers: sequence_numbers.into(),
28        }
29    }
30}
31
32/// The octets of a media packet as they go on the wire: what the FEC protects.
33pub(crate) fn wire_image(packet: &rtp::Packet) -> Result<Bytes, UlpfecError> {
34    let image = packet
35        .marshal()
36        .map_err(|_| UlpfecError::PacketTooLarge)?
37        .freeze();
38    if image.len() < RTP_FIXED_HEADER || image.len() - RTP_FIXED_HEADER > usize::from(u16::MAX) {
39        return Err(UlpfecError::PacketTooLarge);
40    }
41    Ok(image)
42}
43
44/// The 80-bit protected bit string of a media packet (RFC 5109 8.1): the first 64 bits of its RTP
45/// header, then its length minus the 12 octets of the fixed header.
46pub(crate) fn protected_bit_string(image: &[u8]) -> [u8; 10] {
47    let mut bits = [0u8; 10];
48    bits[..8].copy_from_slice(&image[..8]);
49    let length = (image.len() - RTP_FIXED_HEADER) as u16;
50    bits[8..].copy_from_slice(&length.to_be_bytes());
51    bits
52}
53
54/// XOR `source` into `target`, as far as the shorter of the two goes. A source shorter than the
55/// target leaves the rest untouched, which is the zero padding of 8.2.
56pub(crate) fn xor_into(target: &mut [u8], source: &[u8]) {
57    for (target, source) in target.iter_mut().zip(source) {
58        *target ^= source;
59    }
60}
61
62/// The `length` octets of a packet's level starting `offset` octets after the fixed header, as
63/// far as the packet reaches.
64pub(crate) fn level_slice(image: &[u8], offset: usize, length: usize) -> &[u8] {
65    let start = (RTP_FIXED_HEADER + offset).min(image.len());
66    let end = (start + length).min(image.len());
67    &image[start..end]
68}
69
70/// Generates ULPFEC payloads.
71///
72/// Stateless: every call is one FEC packet over the media packets and levels it is given.
73#[derive(Debug, Clone, Copy, Default)]
74pub struct UlpfecEncoder;
75
76impl UlpfecEncoder {
77    /// An encoder.
78    pub fn new() -> Self {
79        Self
80    }
81
82    /// The protection length that covers every packet in `media` to its end: the longest
83    /// packet's length after the fixed RTP header.
84    pub fn full_protection_length(media: &[rtp::Packet]) -> Result<u16, UlpfecError> {
85        let mut longest = 0usize;
86        for packet in media {
87            longest = longest.max(wire_image(packet)?.len() - RTP_FIXED_HEADER);
88        }
89        Ok(longest as u16)
90    }
91
92    /// Generate one FEC packet protecting `media` at `levels` (level 0 first).
93    ///
94    /// The packets are protected as they marshal: CSRC list, header extension, payload and
95    /// padding all count as payload (7.3). Each level names its packets by sequence number; a
96    /// number that is not in `media` is an error, as is a level without packets and a set of
97    /// packets spanning more than 48 sequence numbers. Rule c of 7.4 (a packet holding level `p`
98    /// holds level `p - 1`) holds by construction; rules a and b, which relate several FEC
99    /// packets, are checked by [`validate_scheme`].
100    pub fn encode(
101        &self,
102        media: &[rtp::Packet],
103        levels: &[ProtectionLevel],
104    ) -> Result<UlpfecPacket, UlpfecError> {
105        let mut images = HashMap::with_capacity(media.len());
106        for packet in media {
107            images.insert(packet.header.sequence_number, wire_image(packet)?);
108        }
109        self.encode_images(&images, levels)
110    }
111
112    /// [`encode`](Self::encode) over packets already serialised.
113    pub(crate) fn encode_images(
114        &self,
115        images: &HashMap<u16, Bytes>,
116        levels: &[ProtectionLevel],
117    ) -> Result<UlpfecPacket, UlpfecError> {
118        if levels.is_empty() || levels.iter().any(|level| level.sequence_numbers.is_empty()) {
119            return Err(UlpfecError::NothingToProtect);
120        }
121        let mut protected: Vec<u16> = levels
122            .iter()
123            .flat_map(|level| level.sequence_numbers.iter().copied())
124            .collect();
125        protected.sort_unstable();
126        protected.dedup();
127        if protected
128            .iter()
129            .any(|sequence| !images.contains_key(sequence))
130        {
131            return Err(UlpfecError::UnknownSequenceNumber);
132        }
133
134        // SN base: the lowest protected sequence number, wrap taken into account (7.3). That is
135        // the one from which every other is reached going forward by the least distance.
136        let (sn_base, span) = protected
137            .iter()
138            .map(|base| {
139                let span = protected
140                    .iter()
141                    .map(|sequence| sequence.wrapping_sub(*base))
142                    .max()
143                    .unwrap_or(0);
144                (*base, usize::from(span))
145            })
146            .min_by_key(|(_, span)| *span)
147            .ok_or(UlpfecError::NothingToProtect)?;
148        if span >= LONG_MASK_BITS {
149            return Err(UlpfecError::SpanTooWide);
150        }
151
152        // FEC header: the XOR of the bit strings of the packets protected at level 0 (8.1).
153        let mut bits = [0u8; 10];
154        let mut level0: Vec<u16> = levels[0].sequence_numbers.clone();
155        level0.sort_unstable();
156        level0.dedup();
157        for sequence in &level0 {
158            xor_into(&mut bits, &protected_bit_string(&images[sequence]));
159        }
160
161        let mut out_levels = Vec::with_capacity(levels.len());
162        let mut offset = 0usize;
163        for level in levels {
164            let length = usize::from(level.protection_length);
165            let mut payload = vec![0u8; length];
166            let mut mask = 0u64;
167            let mut sequences = level.sequence_numbers.clone();
168            sequences.sort_unstable();
169            sequences.dedup();
170            for sequence in &sequences {
171                mask |= 1u64 << sequence.wrapping_sub(sn_base);
172                xor_into(&mut payload, level_slice(&images[sequence], offset, length));
173            }
174            out_levels.push(UlpfecLevel {
175                mask,
176                payload: Bytes::from(payload),
177            });
178            offset += length;
179        }
180
181        Ok(UlpfecPacket {
182            long_mask: span >= SHORT_MASK_BITS,
183            padding_recovery: bits[0] & 0x20 != 0,
184            extension_recovery: bits[0] & 0x10 != 0,
185            csrc_count_recovery: bits[0] & 0x0F,
186            marker_recovery: bits[1] & 0x80 != 0,
187            payload_type_recovery: bits[1] & 0x7F,
188            sn_base,
189            timestamp_recovery: u32::from_be_bytes([bits[4], bits[5], bits[6], bits[7]]),
190            length_recovery: u16::from_be_bytes([bits[8], bits[9]]),
191            levels: out_levels,
192        })
193    }
194}
195
196/// Check the mask rules of RFC 5109 7.4 that relate the FEC packets of one group.
197///
198/// `packets` holds the levels of each FEC packet, level 0 first.
199///
200/// - **Rule a.** A media packet is protected at most once at each level above 0. At level 0 it
201///   may be protected by several FEC packets when their level-0 protection lengths are equal.
202/// - **Rule b.** A media packet protected at level `p` is protected at level `p - 1`, in this or
203///   another FEC packet of the group.
204///
205/// Rule c is not checked here because it cannot be broken: a FEC packet's levels are a list.
206pub fn validate_scheme(packets: &[&[ProtectionLevel]]) -> Result<(), UlpfecError> {
207    // (level, sequence number) -> the protection length it was first protected with.
208    let mut seen: HashMap<(usize, u16), u16> = HashMap::new();
209    for levels in packets {
210        if levels.is_empty() {
211            return Err(UlpfecError::NothingToProtect);
212        }
213        for (index, level) in levels.iter().enumerate() {
214            if level.sequence_numbers.is_empty() {
215                return Err(UlpfecError::NothingToProtect);
216            }
217            let mut sequences = level.sequence_numbers.clone();
218            sequences.sort_unstable();
219            sequences.dedup();
220            for sequence in sequences {
221                match seen.insert((index, sequence), level.protection_length) {
222                    None => {}
223                    Some(_) if index > 0 => return Err(UlpfecError::ProtectedTwice),
224                    Some(length) if length != level.protection_length => {
225                        return Err(UlpfecError::ProtectedTwice);
226                    }
227                    Some(_) => {}
228                }
229            }
230        }
231    }
232    for (level, sequence) in seen.keys() {
233        if *level > 0 && !seen.contains_key(&(level - 1, *sequence)) {
234            return Err(UlpfecError::LevelBelowMissing);
235        }
236    }
237    Ok(())
238}
239
240/// Builds the RTP packets of a FEC stream sent apart from the media (RFC 5109 7.2, 14.1).
241///
242/// The sequence number is one higher than the previous FEC packet's, the marker bit is 0, and the
243/// timestamp is the media RTP clock at the instant the FEC packet is sent: the timestamp of the
244/// last media packet, advanced by the time since that packet at the stream's clock rate.
245///
246/// The RFC sets the SSRC to the protected stream's and puts the FEC stream in its own RTP
247/// session. Pass the media SSRC for that. Within one RTP session (a WebRTC transport) the FEC
248/// stream needs an SSRC of its own, since two sequence number spaces cannot share one.
249#[derive(Debug, Clone)]
250pub struct UlpfecStreamPacketizer {
251    payload_type: u8,
252    ssrc: u32,
253    clock_rate: u32,
254    next_sequence_number: u16,
255    /// The last media packet seen: its RTP timestamp and when it was sent.
256    media_clock: Option<(u32, Instant)>,
257}
258
259impl UlpfecStreamPacketizer {
260    /// A packetizer for FEC packets of `payload_type` on `ssrc`, whose first packet has
261    /// `initial_sequence_number`. `clock_rate` is the protected media's.
262    pub fn new(payload_type: u8, ssrc: u32, clock_rate: u32, initial_sequence_number: u16) -> Self {
263        Self {
264            payload_type,
265            ssrc,
266            clock_rate,
267            next_sequence_number: initial_sequence_number,
268            media_clock: None,
269        }
270    }
271
272    /// Note a media packet of the protected stream going out at `now` with `timestamp`.
273    pub fn on_media(&mut self, timestamp: u32, now: Instant) {
274        self.media_clock = Some((timestamp, now));
275    }
276
277    /// The media RTP clock at `now`.
278    fn timestamp_at(&self, now: Instant) -> u32 {
279        match self.media_clock {
280            None => 0,
281            Some((timestamp, at)) => {
282                let elapsed = now.saturating_duration_since(at);
283                let ticks = elapsed.as_micros() * u128::from(self.clock_rate) / 1_000_000;
284                timestamp.wrapping_add(ticks as u32)
285            }
286        }
287    }
288
289    /// The RTP packet carrying `fec`, sent at `now`.
290    pub fn packetize(&mut self, fec: &UlpfecPacket, now: Instant) -> rtp::Packet {
291        let sequence_number = self.next_sequence_number;
292        self.next_sequence_number = self.next_sequence_number.wrapping_add(1);
293        rtp::Packet {
294            header: rtp::header::Header {
295                version: 2,
296                marker: false,
297                payload_type: self.payload_type,
298                sequence_number,
299                timestamp: self.timestamp_at(now),
300                ssrc: self.ssrc,
301                ..Default::default()
302            },
303            payload: fec.marshal(),
304        }
305    }
306}
307
308#[cfg(test)]
309pub(crate) mod tests {
310    use super::*;
311    use std::time::Duration;
312
313    /// A media packet whose payload is a function of its sequence number, so two packets never
314    /// cancel each other by accident.
315    pub(crate) fn media(
316        sequence_number: u16,
317        timestamp: u32,
318        payload_type: u8,
319        marker: bool,
320        payload_length: usize,
321    ) -> rtp::Packet {
322        let payload: Vec<u8> = (0..payload_length)
323            .map(|index| (index as u8).wrapping_mul(31) ^ (sequence_number as u8).wrapping_mul(7))
324            .collect();
325        rtp::Packet {
326            header: rtp::header::Header {
327                version: 2,
328                marker,
329                payload_type,
330                sequence_number,
331                timestamp,
332                ssrc: 2,
333                ..Default::default()
334            },
335            payload: Bytes::from(payload),
336        }
337    }
338
339    /// The four media packets of RFC 5109 section 10: A, B, C and D from SSRC 2, sequence
340    /// numbers 8 to 11, timestamps 3, 5, 7, 9, payload types 11, 18, 11, 18, payloads of 200,
341    /// 140, 100 and 340 octets, marker set on A and C.
342    pub(crate) fn rfc_packets() -> Vec<rtp::Packet> {
343        vec![
344            media(8, 3, 11, true, 200),
345            media(9, 5, 18, false, 140),
346            media(10, 7, 11, true, 100),
347            media(11, 9, 18, false, 340),
348        ]
349    }
350
351    /// RFC 5109 10.1: one level over the four packets, L0 = 340. Figures 7, 8 and 9.
352    #[test]
353    fn rfc_5109_10_1_one_level_matches_the_printed_headers() {
354        let packets = rfc_packets();
355        assert_eq!(
356            Ok(340),
357            UlpfecEncoder::full_protection_length(&packets),
358            "L0 is the longest of 200, 140, 100 and 340"
359        );
360        let fec = UlpfecEncoder::new()
361            .encode(&packets, &[ProtectionLevel::new(340, [8, 9, 10, 11])])
362            .unwrap();
363        let wire = fec.marshal();
364
365        // Figure 8: E 0, L 0, P/X/CC/M/PT recovery 0, SN base 8, TS recovery 8, length 372.
366        assert_eq!(
367            &[0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x08, 0x01, 0x74],
368            &wire[..10]
369        );
370        // Figure 9: L0 340, mask 61440.
371        assert_eq!(&[0x01, 0x54, 0xF0, 0x00], &wire[10..14]);
372        assert_eq!(14 + 340, wire.len(), "the level 0 payload is 340 octets");
373
374        // Figure 7: the RTP header of the FEC packet, sent in its own session on the media SSRC.
375        let now = Instant::now();
376        let mut packetizer = UlpfecStreamPacketizer::new(127, 2, 8000, 1);
377        for packet in &packets {
378            packetizer.on_media(packet.header.timestamp, now);
379        }
380        let rtp_packet = packetizer.packetize(&fec, now);
381        let rtp_wire = rtp_packet.marshal().unwrap();
382        assert_eq!(
383            &[
384                0x80, 0x7F, 0x00, 0x01, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00, 0x02
385            ],
386            &rtp_wire[..12]
387        );
388    }
389
390    /// RFC 5109 10.2: two FEC packets, L0 = 70 and L1 = 90. Figures 12, 13, 15, 16 and 17.
391    #[test]
392    fn rfc_5109_10_2_two_levels_match_the_printed_headers() {
393        let packets = rfc_packets();
394        let first = [ProtectionLevel::new(70, [8, 9])];
395        let second = [
396            ProtectionLevel::new(70, [10, 11]),
397            ProtectionLevel::new(90, [8, 9, 10, 11]),
398        ];
399        validate_scheme(&[&first, &second]).expect("the scheme of Figure 10 follows 7.4");
400
401        let encoder = UlpfecEncoder::new();
402        let wire1 = encoder.encode(&packets, &first).unwrap().marshal();
403        // Figure 12: PT recovery 25, SN base 8, TS recovery 6, length recovery 68. The figure
404        // prints M recovery as 0, with the four-packet sum of 10.1 as its reason; over the two
405        // packets this FEC packet protects at level 0 (A with the marker, B without) the
406        // operation of 8.1 gives 1, which is what a receiver needs to rebuild either.
407        assert_eq!(
408            &[0x00, 0x99, 0x00, 0x08, 0x00, 0x00, 0x00, 0x06, 0x00, 0x44],
409            &wire1[..10]
410        );
411        // Figure 13: L0 70, mask 49152.
412        assert_eq!(&[0x00, 0x46, 0xC0, 0x00], &wire1[10..14]);
413        assert_eq!(14 + 70, wire1.len());
414
415        let fec2 = encoder.encode(&packets, &second).unwrap();
416        let wire2 = fec2.marshal();
417        // Figure 15: PT recovery 25, SN base 8 (the lowest over both levels), TS recovery 14,
418        // length recovery 304. M recovery is 1 for the same reason (C with the marker, D without).
419        assert_eq!(
420            &[0x00, 0x99, 0x00, 0x08, 0x00, 0x00, 0x00, 0x0E, 0x01, 0x30],
421            &wire2[..10]
422        );
423        // Figure 16: L0 70, mask 12288.
424        assert_eq!(&[0x00, 0x46, 0x30, 0x00], &wire2[10..14]);
425        // Figure 17: L1 90, mask 61440, after the 70 octets of level 0.
426        assert_eq!(&[0x00, 0x5A, 0xF0, 0x00], &wire2[84..88]);
427        assert_eq!(14 + 70 + 4 + 90, wire2.len());
428
429        // Figures 11 and 14: sequence numbers 1 and 2, timestamps 5 and 9 (the media clock when
430        // each is sent: after B, and after D). The figures print the marker bit as 1; 7.2 says
431        // it SHALL be 0, and 0 is what is sent.
432        let now = Instant::now();
433        let mut packetizer = UlpfecStreamPacketizer::new(127, 2, 8000, 1);
434        packetizer.on_media(3, now);
435        packetizer.on_media(5, now);
436        let rtp1 = packetizer.packetize(&encoder.encode(&packets, &first).unwrap(), now);
437        packetizer.on_media(7, now);
438        packetizer.on_media(9, now);
439        let rtp2 = packetizer.packetize(&fec2, now);
440        assert_eq!((1, 5, 2, 127), header_fields(&rtp1));
441        assert_eq!((2, 9, 2, 127), header_fields(&rtp2));
442        assert!(!rtp1.header.marker && !rtp2.header.marker);
443    }
444
445    fn header_fields(packet: &rtp::Packet) -> (u16, u32, u32, u8) {
446        (
447            packet.header.sequence_number,
448            packet.header.timestamp,
449            packet.header.ssrc,
450            packet.header.payload_type,
451        )
452    }
453
454    #[test]
455    fn the_level_payload_is_the_xor_with_short_packets_padded_by_zero() {
456        let packets = vec![media(1, 0, 96, false, 4), media(2, 0, 96, false, 2)];
457        let fec = UlpfecEncoder::new()
458            .encode(&packets, &[ProtectionLevel::new(6, [1, 2])])
459            .unwrap();
460        let a = &packets[0].payload;
461        let b = &packets[1].payload;
462        assert_eq!(
463            &[a[0] ^ b[0], a[1] ^ b[1], a[2], a[3], 0, 0],
464            &fec.levels[0].payload[..],
465            "the shorter packet counts as zeros, and so does everything past the longest"
466        );
467        assert_eq!(4 ^ 2, fec.length_recovery);
468    }
469
470    #[test]
471    fn a_higher_level_starts_where_the_levels_below_end() {
472        let packets = vec![media(1, 0, 96, false, 10), media(2, 0, 96, false, 10)];
473        let fec = UlpfecEncoder::new()
474            .encode(
475                &packets,
476                &[
477                    ProtectionLevel::new(3, [1, 2]),
478                    ProtectionLevel::new(4, [1, 2]),
479                ],
480            )
481            .unwrap();
482        let a = &packets[0].payload;
483        let b = &packets[1].payload;
484        let expected: Vec<u8> = (3..7).map(|index| a[index] ^ b[index]).collect();
485        assert_eq!(&expected[..], &fec.levels[1].payload[..]);
486    }
487
488    #[test]
489    fn csrc_extension_and_padding_count_as_payload() {
490        let mut with_everything = media(1, 0, 96, false, 5);
491        with_everything.header.csrc = vec![0xAABB_CCDD];
492        with_everything.header.padding = true;
493        with_everything.header.padding_size = 3;
494        with_everything
495            .header
496            .set_extension(1, Bytes::from_static(&[0x42]))
497            .unwrap();
498        let plain = media(2, 0, 96, false, 5);
499        let wire = with_everything.marshal().unwrap();
500
501        let fec = UlpfecEncoder::new()
502            .encode(
503                &[with_everything, plain.clone()],
504                &[ProtectionLevel::new(40, [1, 2])],
505            )
506            .unwrap();
507
508        assert!(fec.padding_recovery && fec.extension_recovery);
509        assert_eq!(1, fec.csrc_count_recovery);
510        assert_eq!(
511            (wire.len() - 12) as u16 ^ 5,
512            fec.length_recovery,
513            "length is everything after the fixed header"
514        );
515        let mut expected = wire[12..].to_vec();
516        expected.resize(40, 0);
517        xor_into(&mut expected, &plain.payload);
518        assert_eq!(&expected[..], &fec.levels[0].payload[..]);
519    }
520
521    #[test]
522    fn the_sn_base_is_the_lowest_sequence_number_across_a_wrap() {
523        let packets = vec![
524            media(65534, 0, 96, false, 3),
525            media(65535, 0, 96, false, 3),
526            media(0, 0, 96, false, 3),
527            media(1, 0, 96, false, 3),
528        ];
529        let fec = UlpfecEncoder::new()
530            .encode(&packets, &[ProtectionLevel::new(3, [0, 1, 65535, 65534])])
531            .unwrap();
532        assert_eq!(65534, fec.sn_base);
533        assert_eq!(0b1111, fec.levels[0].mask);
534        assert!(!fec.long_mask);
535    }
536
537    #[test]
538    fn the_sn_base_covers_packets_protected_only_at_a_higher_level() {
539        let packets = rfc_packets();
540        let fec = UlpfecEncoder::new()
541            .encode(
542                &packets,
543                &[
544                    ProtectionLevel::new(70, [10, 11]),
545                    ProtectionLevel::new(90, [8, 9, 10, 11]),
546                ],
547            )
548            .unwrap();
549        assert_eq!(8, fec.sn_base);
550        assert_eq!(0b1100, fec.levels[0].mask);
551        assert_eq!(0b1111, fec.levels[1].mask);
552    }
553
554    #[test]
555    fn a_span_beyond_sixteen_packets_uses_the_long_mask() {
556        let packets: Vec<_> = (100..148).map(|seq| media(seq, 0, 96, false, 2)).collect();
557        let encoder = UlpfecEncoder::new();
558        let short = encoder
559            .encode(&packets, &[ProtectionLevel::new(2, [100, 115])])
560            .unwrap();
561        assert!(!short.long_mask, "offset 15 fits the 16-bit mask");
562        let long = encoder
563            .encode(&packets, &[ProtectionLevel::new(2, [100, 116, 147])])
564            .unwrap();
565        assert!(long.long_mask);
566        assert_eq!(
567            vec![0, 16, 47],
568            long.levels[0].offsets().collect::<Vec<_>>()
569        );
570        assert_eq!(long, UlpfecPacket::parse(&long.marshal()).unwrap());
571    }
572
573    #[test]
574    fn more_than_forty_eight_sequence_numbers_cannot_be_protected() {
575        let packets: Vec<_> = (100..149).map(|seq| media(seq, 0, 96, false, 2)).collect();
576        assert_eq!(
577            Err(UlpfecError::SpanTooWide),
578            UlpfecEncoder::new().encode(&packets, &[ProtectionLevel::new(2, [100, 148])])
579        );
580    }
581
582    #[test]
583    fn a_level_must_name_packets_that_were_given() {
584        let packets = rfc_packets();
585        let encoder = UlpfecEncoder::new();
586        assert_eq!(
587            Err(UlpfecError::UnknownSequenceNumber),
588            encoder.encode(&packets, &[ProtectionLevel::new(10, [8, 12])])
589        );
590        assert_eq!(
591            Err(UlpfecError::NothingToProtect),
592            encoder.encode(&packets, &[])
593        );
594        assert_eq!(
595            Err(UlpfecError::NothingToProtect),
596            encoder.encode(&packets, &[ProtectionLevel::new(10, Vec::new())])
597        );
598    }
599
600    #[test]
601    fn a_packet_protected_twice_above_level_0_is_refused() {
602        let first = [
603            ProtectionLevel::new(10, [1, 2]),
604            ProtectionLevel::new(10, [1, 2]),
605        ];
606        let second = [
607            ProtectionLevel::new(10, [3, 4]),
608            ProtectionLevel::new(10, [2, 3, 4]),
609        ];
610        assert_eq!(
611            Err(UlpfecError::ProtectedTwice),
612            validate_scheme(&[&first, &second])
613        );
614    }
615
616    #[test]
617    fn level_0_may_protect_a_packet_twice_only_with_equal_lengths() {
618        let first = [ProtectionLevel::new(10, [1, 2])];
619        let same_length = [ProtectionLevel::new(10, [2, 3])];
620        let other_length = [ProtectionLevel::new(12, [2, 3])];
621        assert_eq!(Ok(()), validate_scheme(&[&first, &same_length]));
622        assert_eq!(
623            Err(UlpfecError::ProtectedTwice),
624            validate_scheme(&[&first, &other_length])
625        );
626    }
627
628    #[test]
629    fn a_level_needs_the_level_below_for_the_same_packet() {
630        let first = [ProtectionLevel::new(10, [1, 2])];
631        let second = [
632            ProtectionLevel::new(10, [3]),
633            ProtectionLevel::new(10, [1, 2, 3, 4]),
634        ];
635        assert_eq!(
636            Err(UlpfecError::LevelBelowMissing),
637            validate_scheme(&[&first, &second]),
638            "packet 4 is protected at level 1 and nowhere at level 0"
639        );
640    }
641
642    #[test]
643    fn a_fec_stream_counts_its_own_sequence_numbers_and_follows_the_media_clock() {
644        let fec = UlpfecEncoder::new()
645            .encode(&rfc_packets(), &[ProtectionLevel::new(1, [8])])
646            .unwrap();
647        let start = Instant::now();
648        let mut packetizer = UlpfecStreamPacketizer::new(100, 7, 90_000, 65535);
649        packetizer.on_media(1000, start);
650
651        let first = packetizer.packetize(&fec, start + Duration::from_millis(10));
652        let second = packetizer.packetize(&fec, start + Duration::from_millis(20));
653
654        assert_eq!(65535, first.header.sequence_number);
655        assert_eq!(0, second.header.sequence_number, "one higher, with wrap");
656        assert_eq!(1000 + 900, first.header.timestamp, "10 ms at 90 kHz");
657        assert_eq!(1000 + 1800, second.header.timestamp);
658        assert!(!first.header.marker);
659        assert_eq!(7, first.header.ssrc);
660    }
661}