rtci-interceptor 0.5.0

Sans-I/O RTP/RTCP interceptor pipeline for WebRTC: RTCP reports, NACK, TWCC, congestion control, pacing, FEC
Documentation
//! Long-run soak: transport-wide feedback (draft-holmer-rmcat-transport-wide-cc-extensions-01)
//! across the wrap of its 16-bit sequence number, four times over, on a path that loses,
//! reorders and duplicates packets. The receiver's recorder builds the feedback, it crosses the
//! wire (marshalled and parsed), and the sender's timeline and history turn it into the reports
//! congestion control reads. Deterministic (a fixed generator), virtual time, no sleeping.

use super::acknowledgement::PacketReport;
use super::convert::FeedbackTimeline;
use super::history::History;
use crate::twcc::recorder::Recorder;
use rtcp::transport_feedbacks::transport_layer_cc::TransportLayerCc;
use shared::marshal::Unmarshal;
use std::cmp::Reverse;
use std::collections::BinaryHeap;
use std::time::{Duration, Instant};

/// A fixed linear congruential generator: the same path every run.
struct Lcg(u64);

impl Lcg {
    fn chance(&mut self, per_mille: u64) -> bool {
        self.0 = self
            .0
            .wrapping_mul(6_364_136_223_846_793_005)
            .wrapping_add(1_442_695_040_888_963_407);
        (self.0 >> 33) % 1000 < per_mille
    }
}

/// One packet a millisecond from transport-wide number 65000, for four wraps and then some;
/// 2 % lost, 5 % 3 ms late (overtaken by the next two), 1 % delivered twice. Feedback every
/// 50 ms, and now and then after 1.5 s, which splits into several messages. Every packet up to
/// the last feedback is reported once: as received, with its arrival time to the microsecond
/// (or without one, when an earlier message had reported it missing), or as lost exactly when
/// the path lost it. No feedback message reads as lost, nothing is released without a report.
#[test]
fn transport_wide_feedback_stays_exact_across_four_sequence_wraps() {
    const FIRST: u16 = 65_000;
    const PACKETS: usize = 4 * 65_536 + 3_000;
    let epoch = Instant::now();
    let mut path = Lcg(0x5eed_f7ec);
    let mut history = History::new();
    let mut recorder = Recorder::new(1);
    let mut timeline = FeedbackTimeline::new();
    // The first arrival of each packet, in microseconds, by send order.
    let mut delivered: Vec<Option<i64>> = vec![None; PACKETS];
    let mut in_flight: BinaryHeap<Reverse<(i64, usize)>> = BinaryHeap::new();
    let mut reports: Vec<PacketReport> = vec![];
    let mut messages = 0usize;
    let mut split_rounds = 0usize;
    let mut wraps = 0;
    let mut next_feedback = 50_000i64;

    let mut feed_back = |now: i64,
                         recorder: &mut Recorder,
                         history: &mut History,
                         reports: &mut Vec<PacketReport>,
                         messages: &mut usize,
                         split_rounds: &mut usize| {
        let packets = recorder.build_feedback_packet();
        if packets.len() > 1 {
            *split_rounds += 1;
        }
        for packet in packets {
            let mut raw = packet.marshal().expect("feedback marshals");
            let feedback = TransportLayerCc::unmarshal(&mut raw).expect("and parses");
            *messages += 1;
            assert_eq!(0, history.on_twcc_feedback_count(feedback.fb_pkt_count));
            let received_at = epoch + Duration::from_micros(now as u64);
            for acknowledgement in timeline.convert_twcc(&feedback) {
                history.on_twcc_feedback(received_at, acknowledgement);
            }
        }
        reports.extend(history.take_reports());
    };

    for id in 0..PACKETS {
        let now = id as i64 * 1_000;
        let sequence_number = FIRST.wrapping_add(id as u16);
        if id > 0 && sequence_number == 0 {
            wraps += 1;
        }
        history.add_outgoing(
            7,
            id as u16,
            true,
            sequence_number,
            1_200,
            epoch + Duration::from_micros(now as u64),
        );
        if !path.chance(20) {
            let arrival = now + if path.chance(50) { 23_000 } else { 20_000 };
            in_flight.push(Reverse((arrival, id)));
            if path.chance(10) {
                in_flight.push(Reverse((arrival + 1_000, id)));
            }
        }
        while let Some(&Reverse((arrival, id))) = in_flight.peek() {
            if arrival > now {
                break;
            }
            in_flight.pop();
            recorder.record(7, FIRST.wrapping_add(id as u16), arrival);
            delivered[id].get_or_insert(arrival);
        }
        if now >= next_feedback {
            feed_back(
                now,
                &mut recorder,
                &mut history,
                &mut reports,
                &mut messages,
                &mut split_rounds,
            );
            next_feedback += if messages % 97 == 50 {
                1_500_000
            } else {
                50_000
            };
        }
    }
    let end = PACKETS as i64 * 1_000 + 30_000;
    while let Some(Reverse((arrival, id))) = in_flight.pop() {
        recorder.record(7, FIRST.wrapping_add(id as u16), arrival);
        delivered[id].get_or_insert(arrival);
    }
    feed_back(
        end,
        &mut recorder,
        &mut history,
        &mut reports,
        &mut messages,
        &mut split_rounds,
    );

    assert!(wraps >= 4, "{wraps} wraps");
    assert!(split_rounds > 0, "some rounds took several messages");
    assert_eq!(0, history.lost_feedback());
    assert_eq!(0, history.unreported(), "every packet was described");
    assert!(
        history.recovered() > 0,
        "reordering crossed a feedback boundary"
    );

    let mut seen = vec![false; PACKETS];
    let mut origin: Option<i64> = None;
    let mut timed = 0usize;
    for report in &reports {
        let id = report.id as usize;
        assert!(!seen[id], "packet {id} reported twice");
        seen[id] = true;
        assert_eq!(FIRST.wrapping_add(id as u16), report.twcc_sequence_number);
        assert_eq!(
            delivered[id].is_some(),
            report.arrived,
            "packet {id} ({}): delivered {:?}",
            report.twcc_sequence_number,
            delivered[id]
        );
        if let (Some(at), Some(arrival)) = (delivered[id], report.arrival) {
            // The receiver's clock has its own origin; it is the same for every report.
            let reported = arrival.as_micros() as i64;
            let origin = *origin.get_or_insert(reported - at);
            assert_eq!(
                at,
                reported - origin,
                "packet {id} ({})",
                report.twcc_sequence_number
            );
            timed += 1;
        }
    }
    // The last packets (at most one feedback interval and the path delay) may wait for a
    // feedback that never comes; everything before them was reported.
    let reported = seen.iter().take_while(|seen| **seen).count();
    assert!(
        reported >= PACKETS - 2_000,
        "only the first {reported} of {PACKETS} were reported in order"
    );
    assert!(timed > PACKETS * 9 / 10, "{timed} arrival times checked");
}