Skip to main content

rtci_interceptor/rtpfb/
history.rs

1//! What was sent, joined with what the receiver said about it.
2
3use super::acknowledgement::{Acknowledgement, PacketReport};
4use rtcp::transport_feedbacks::cc_feedback_report::Ecn;
5use std::collections::HashMap;
6use std::time::{Duration, Instant};
7
8/// Records outgoing packets and matches incoming feedback against them.
9///
10/// The two feedback formats identify a packet differently — TWCC by its own transport-wide
11/// sequence number, RFC 8888 by the stream's SSRC and RTP sequence number — so both indexes are
12/// kept, pointing at one record.
13#[derive(Debug, Default)]
14pub struct History {
15    /// Monotonic id, so reports come out in send order however sequence numbers wrap.
16    next_id: u64,
17    packets: HashMap<u64, Sent>,
18    twcc_index: HashMap<u16, u64>,
19    ssrc_sequence_index: HashMap<(u32, u16), u64>,
20    /// Highest id acknowledged so far.
21    highest_acknowledged: Option<u64>,
22    /// Lowest id not yet reported to the consumer.
23    next_to_report: u64,
24    /// The `fb_pkt_count` of the last TWCC feedback read.
25    last_feedback_count: Option<u8>,
26    /// Feedback packets the count shows were sent and never read.
27    lost_feedback: u64,
28    /// Sent packets no feedback ever described, released without a verdict.
29    unreported: u64,
30    /// Packets a feedback reported as not received, held back for one more feedback: a
31    /// packet only overtaken on the path arrives after the report that named it missing.
32    pending_losses: Vec<u64>,
33    /// Packets reported as not received and then as received by a later feedback.
34    recovered: u64,
35    /// The first packet sent on the path in use, once a path was left
36    /// ([`forget_sent`](Self::forget_sent)).
37    path_begins: Option<u64>,
38    /// The earliest packet sent on the path in use that a feedback reported received.
39    first_arrival: Option<u64>,
40    /// Packets sent on a new path before anything arrived over it and reported as not
41    /// received: released without a verdict.
42    before_the_path_carried: u64,
43}
44
45/// A sent packet and whether any feedback has described it yet.
46#[derive(Debug)]
47struct Sent {
48    report: PacketReport,
49    /// A feedback packet named this packet, as received or as not received. A packet no
50    /// feedback named has no verdict: the report that would have carried it was lost, or the
51    /// receiver does not report on its stream at all.
52    covered: bool,
53}
54
55impl History {
56    /// An empty history.
57    pub fn new() -> Self {
58        Self::default()
59    }
60
61    /// How many packets are being tracked.
62    pub fn len(&self) -> usize {
63        self.packets.len()
64    }
65
66    /// Whether nothing is being tracked.
67    pub fn is_empty(&self) -> bool {
68        self.packets.is_empty()
69    }
70
71    /// Record a packet as it leaves.
72    ///
73    /// `departure` must be the instant the packet was **released** to the network, not the
74    /// instant the application handed it over. A pacer can hold a packet for tens of
75    /// milliseconds, and counting that as network delay is exactly the error that makes a
76    /// bandwidth estimate collapse (chain contract rule 3).
77    #[allow(clippy::too_many_arguments)]
78    pub fn add_outgoing(
79        &mut self,
80        ssrc: u32,
81        rtp_sequence_number: u16,
82        is_twcc: bool,
83        twcc_sequence_number: u16,
84        size: usize,
85        departure: Instant,
86    ) -> u64 {
87        let id = self.next_id;
88        self.next_id += 1;
89
90        if is_twcc
91            && let Some(previous) = self.twcc_index.insert(twcc_sequence_number, id)
92            && let Some(earlier) = self.packets.get_mut(&previous)
93        {
94            // The same transport-wide number again: a retransmission sent as it was (no RTX),
95            // which keeps its number. The receiver reports a number once, so its verdict goes
96            // to this transmission; the earlier one was asked for again because it did not
97            // arrive, and is reported as the loss it was.
98            earlier.covered = true;
99        }
100        self.ssrc_sequence_index
101            .insert((ssrc, rtp_sequence_number), id);
102
103        self.packets.insert(
104            id,
105            Sent {
106                report: PacketReport {
107                    ssrc,
108                    id,
109                    rtp_sequence_number,
110                    is_twcc,
111                    twcc_sequence_number,
112                    size,
113                    arrived: false,
114                    departure,
115                    arrival: None,
116                    ecn: Ecn::NotEct,
117                },
118                covered: false,
119            },
120        );
121
122        id
123    }
124
125    /// Apply TWCC feedback, returning the round trip time it implies.
126    ///
127    /// `None` when the feedback names a packet this endpoint has no record of — which happens
128    /// routinely at startup and after the history has been pruned, and is not an error.
129    pub fn on_twcc_feedback(
130        &mut self,
131        received_at: Instant,
132        acknowledgement: Acknowledgement,
133    ) -> Option<Duration> {
134        let Some(&id) = self.twcc_index.get(&acknowledgement.sequence_number) else {
135            if acknowledgement.arrived {
136                log::debug!(
137                    "rtpfb: transport-wide {} reported received matches no packet held (released, or never sent)",
138                    acknowledgement.sequence_number
139                );
140            }
141            return None;
142        };
143        if acknowledgement.arrived
144            && self
145                .packets
146                .get(&id)
147                .is_some_and(|sent| sent.covered && !sent.report.arrived)
148        {
149            log::debug!(
150                "rtpfb: transport-wide {} reported received after a feedback reported it lost",
151                acknowledgement.sequence_number
152            );
153        }
154        self.apply(received_at, id, acknowledgement)
155    }
156
157    /// Apply RFC 8888 feedback for one stream, returning the round trip time it implies.
158    pub fn on_ccfb_feedback(
159        &mut self,
160        received_at: Instant,
161        ssrc: u32,
162        acknowledgement: Acknowledgement,
163    ) -> Option<Duration> {
164        let Some(&id) = self
165            .ssrc_sequence_index
166            .get(&(ssrc, acknowledgement.sequence_number))
167        else {
168            if acknowledgement.arrived {
169                log::debug!(
170                    "rtpfb: {ssrc:#x} {} reported received matches no packet held (released, or never sent)",
171                    acknowledgement.sequence_number
172                );
173            }
174            return None;
175        };
176        if acknowledgement.arrived
177            && self
178                .packets
179                .get(&id)
180                .is_some_and(|sent| sent.covered && !sent.report.arrived)
181        {
182            log::debug!(
183                "rtpfb: {ssrc:#x} {} reported received after a feedback reported it lost",
184                acknowledgement.sequence_number
185            );
186        }
187        self.apply(received_at, id, acknowledgement)
188    }
189
190    fn apply(
191        &mut self,
192        received_at: Instant,
193        id: u64,
194        acknowledgement: Acknowledgement,
195    ) -> Option<Duration> {
196        let sent = self.packets.get_mut(&id)?;
197        sent.covered = true;
198        let packet = &mut sent.report;
199
200        packet.arrived = acknowledgement.arrived;
201        packet.arrival = acknowledgement.arrival;
202        packet.ecn = acknowledgement.ecn;
203
204        if packet.arrived {
205            self.highest_acknowledged = Some(match self.highest_acknowledged {
206                Some(highest) => highest.max(id),
207                None => id,
208            });
209        }
210
211        // Round trip: this feedback arrived now, and the packet left then. Both instants are on
212        // this endpoint's clock, so unlike the arrival times this is a real duration.
213        Some(received_at.saturating_duration_since(packet.departure))
214    }
215
216    /// Note the feedback packet count of a TWCC feedback just read, and return how many feedback
217    /// packets the receiver sent between the previous one and this one that never arrived.
218    ///
219    /// The count is the only thing that tells a lost feedback packet from a quiet receiver
220    /// (draft-holmer-rmcat-transport-wide-cc-extensions-01 section 3.1). The packets a lost
221    /// feedback would have described get no verdict at all, see
222    /// [`take_reports`](Self::take_reports); this is the measure of how often that happened.
223    pub fn on_twcc_feedback_count(&mut self, feedback_packet_count: u8) -> u8 {
224        let missed = match self.last_feedback_count {
225            // A count at or behind the last one is a reordered or repeated feedback: nothing
226            // is known to be missing.
227            Some(last) => {
228                let ahead = feedback_packet_count.wrapping_sub(last);
229                if ahead == 0 || ahead > 127 {
230                    return 0;
231                }
232                ahead - 1
233            }
234            None => 0,
235        };
236        self.last_feedback_count = Some(feedback_packet_count);
237        self.lost_feedback += u64::from(missed);
238        missed
239    }
240
241    /// How many TWCC feedback packets were sent by the receiver and never read here.
242    pub fn lost_feedback(&self) -> u64 {
243        self.lost_feedback
244    }
245
246    /// How many sent packets were released without any feedback describing them.
247    pub fn unreported(&self) -> u64 {
248        self.unreported
249    }
250
251    /// Take every packet a feedback described, up to the highest *arrived* one, since the last
252    /// call, in send order.
253    ///
254    /// A packet the receiver reported as not received is a loss. A packet below the highest
255    /// arrival that **no feedback described** is neither: the feedback that covered it was lost,
256    /// or the receiver does not report on its stream (no transport-wide sequence number, an SSRC
257    /// outside the RFC 8888 report). The draft is explicit that such packets are ignored, not
258    /// counted as lost or received (section 3), so they are released here without a report.
259    /// Loss feedback alone does not advance the reporting window; losses are emitted when a later
260    /// packet is reported as arrived.
261    ///
262    /// After a path was left ([`forget_sent`](Self::forget_sent)), a packet sent on the new
263    /// path earlier than every packet reported received over it, and reported as not received,
264    /// has no verdict either: see [`before_the_path_carried`](Self::before_the_path_carried).
265    pub fn take_reports(&mut self) -> Vec<PacketReport> {
266        let mut reports = self.take_described();
267        if let Some(path_begins) = self.path_begins {
268            for report in &reports {
269                if report.arrived && report.id >= path_begins {
270                    self.first_arrival = Some(
271                        self.first_arrival
272                            .map_or(report.id, |first| first.min(report.id)),
273                    );
274                }
275            }
276            let first_arrival = self.first_arrival;
277            let before = reports.len();
278            reports.retain(|report| {
279                report.arrived
280                    || report.id < path_begins
281                    || first_arrival.is_some_and(|first| report.id > first)
282            });
283            self.before_the_path_carried += (before - reports.len()) as u64;
284        }
285        reports
286    }
287
288    /// Every packet a feedback described since the last call, in send order.
289    fn take_described(&mut self) -> Vec<PacketReport> {
290        let mut reports = Vec::new();
291        // The losses the previous call held back: lost after all, or received meanwhile. A
292        // packet received late is reported as received but without its arrival time: it
293        // counts for the loss fraction, while the delay model, which reads reports in send
294        // order, does not see an old packet among new ones.
295        for id in std::mem::take(&mut self.pending_losses) {
296            if let Some(sent) = self.release(id) {
297                let mut packet = sent.report;
298                if packet.arrived {
299                    self.recovered += 1;
300                    packet.arrival = None;
301                }
302                reports.push(packet);
303            }
304        }
305        let Some(highest) = self.highest_acknowledged else {
306            return reports;
307        };
308        if self.next_to_report > highest {
309            return reports;
310        }
311        for id in self.next_to_report..=highest {
312            // Held only while a later feedback can still name it: a transmission superseded
313            // under the same number never will.
314            let held = self.packets.get(&id).is_some_and(|sent| {
315                let packet = &sent.report;
316                let reachable = if packet.is_twcc {
317                    self.twcc_index.get(&packet.twcc_sequence_number) == Some(&id)
318                } else {
319                    self.ssrc_sequence_index
320                        .get(&(packet.ssrc, packet.rtp_sequence_number))
321                        == Some(&id)
322                };
323                sent.covered && !packet.arrived && reachable
324            });
325            if held {
326                // A loss is final only when the next feedback has not reported it received
327                // either (libwebrtc's TransportFeedbackAdapter keeps a lost packet "because
328                // it might be reported as received by a later feedback").
329                self.pending_losses.push(id);
330                continue;
331            }
332            if let Some(sent) = self.release(id) {
333                if sent.covered {
334                    reports.push(sent.report);
335                } else {
336                    self.unreported += 1;
337                }
338            }
339        }
340        self.next_to_report = highest + 1;
341
342        reports
343    }
344
345    /// Take a packet out of the history and its indexes.
346    fn release(&mut self, id: u64) -> Option<Sent> {
347        let sent = self.packets.remove(&id)?;
348        let packet = &sent.report;
349        if packet.is_twcc && self.twcc_index.get(&packet.twcc_sequence_number) == Some(&id) {
350            self.twcc_index.remove(&packet.twcc_sequence_number);
351        }
352        if self
353            .ssrc_sequence_index
354            .get(&(packet.ssrc, packet.rtp_sequence_number))
355            == Some(&id)
356        {
357            self.ssrc_sequence_index
358                .remove(&(packet.ssrc, packet.rtp_sequence_number));
359        }
360        Some(sent)
361    }
362
363    /// Forget every packet sent so far, as on a new path: those went into the path that was
364    /// left, and what a later feedback says of them is neither a loss nor a delivery of the new
365    /// one's. libwebrtc's `TransportFeedbackAdapter::SetNetworkRoute` does the same, so that
366    /// "the feedback adapter only reports packets sent on the new route"
367    /// (`RtpTransportControllerSend::OnNetworkRouteChanged`). A feedback that names one of
368    /// them later matches nothing, as for a packet pruned.
369    pub fn forget_sent(&mut self) {
370        self.packets.clear();
371        self.twcc_index.clear();
372        self.ssrc_sequence_index.clear();
373        self.pending_losses.clear();
374        self.highest_acknowledged = None;
375        self.next_to_report = self.next_id;
376        self.path_begins = Some(self.next_id);
377        self.first_arrival = None;
378    }
379
380    /// Packets sent on a new path before the first packet that arrived over it, reported as
381    /// not received, and released without a verdict.
382    ///
383    /// The two ends of a path do not begin to use it at the same instant: what this endpoint
384    /// sends between its own change (the peer connection's word, or the first packets from new
385    /// addresses) and the moment the path carries media the other way round as well (the
386    /// peer's own selection of the pair, a relay's permission, an address binding) goes
387    /// nowhere. Those packets are in the same case as the ones sent into the path that was
388    /// left: they say nothing of what the new path carries, and the estimate that has just
389    /// started over is not lowered for them (RFC 8836 section 2, requirement 1: the reaction is
390    /// to the path's capacity). A packet lost after one that arrived is a loss as ever.
391    pub fn before_the_path_carried(&self) -> u64 {
392        self.before_the_path_carried
393    }
394
395    /// Packets reported as not received that a later feedback reported as received.
396    pub fn recovered(&self) -> u64 {
397        self.recovered
398    }
399
400    /// Drop records of packets sent before `cutoff` that were never acknowledged.
401    ///
402    /// Without this the history grows without bound on a lossy path: an unacknowledged packet is
403    /// never reported and never removed, so nothing else would ever release it.
404    pub fn prune_before(&mut self, cutoff: Instant) {
405        let stale: Vec<u64> = self
406            .packets
407            .iter()
408            .filter(|(_, sent)| sent.report.departure < cutoff && !sent.report.arrived)
409            .map(|(&id, _)| id)
410            .collect();
411
412        for id in stale {
413            if let Some(sent) = self.packets.remove(&id) {
414                let packet = sent.report;
415                // Only a TWCC packet has an entry under its transport-wide sequence number. A
416                // non-TWCC packet carries whatever the caller passed — typically 0 — and removing
417                // that key would evict whichever real TWCC packet holds it.
418                if packet.is_twcc {
419                    self.twcc_index.remove(&packet.twcc_sequence_number);
420                }
421                self.ssrc_sequence_index
422                    .remove(&(packet.ssrc, packet.rtp_sequence_number));
423            }
424        }
425    }
426}
427
428#[cfg(test)]
429mod tests {
430    use super::*;
431
432    fn history_with_three_packets(now: Instant) -> History {
433        let mut history = History::new();
434        for sequence_number in 0..3u16 {
435            history.add_outgoing(1, 100 + sequence_number, true, sequence_number, 1200, now);
436        }
437        history
438    }
439
440    #[test]
441    fn feedback_for_an_unknown_packet_is_ignored() {
442        let now = Instant::now();
443        let mut history = History::new();
444
445        assert_eq!(
446            None,
447            history.on_twcc_feedback(now, Acknowledgement::received(5, None, Ecn::NotEct)),
448            "nothing was sent with that sequence number"
449        );
450        assert!(history.take_reports().is_empty());
451    }
452
453    #[test]
454    fn twcc_feedback_matches_by_transport_wide_sequence_number() {
455        let now = Instant::now();
456        let mut history = history_with_three_packets(now);
457
458        let rtt = history.on_twcc_feedback(
459            now + Duration::from_millis(80),
460            Acknowledgement::received(1, Some(Duration::from_millis(5)), Ecn::NotEct),
461        );
462        assert_eq!(Some(Duration::from_millis(80)), rtt);
463
464        let reports = history.take_reports();
465        assert_eq!(1, reports.len(), "only what the feedback described");
466        assert_eq!(101, reports[0].rtp_sequence_number);
467        assert!(reports[0].arrived);
468    }
469
470    /// draft-holmer-rmcat-transport-wide-cc-extensions-01 section 3: when a feedback packet is
471    /// lost, the packets it would have reported are ignored, "not counted as lost or received".
472    #[test]
473    fn packets_whose_feedback_was_lost_are_not_reported_as_lost() {
474        let now = Instant::now();
475        let mut history = History::new();
476        for sequence_number in 0..20u16 {
477            history.add_outgoing(1, 100 + sequence_number, true, sequence_number, 1200, now);
478        }
479
480        // The feedback for 0..=9 never arrives; the one for 10..=19 does.
481        for sequence_number in 10..20u16 {
482            history.on_twcc_feedback(
483                now + Duration::from_millis(50),
484                Acknowledgement::received(sequence_number, None, Ecn::NotEct),
485            );
486        }
487
488        let reports = history.take_reports();
489        assert_eq!(10, reports.len(), "the ten packets the feedback described");
490        assert!(
491            reports.iter().all(|report| report.arrived),
492            "no loss was reported by the receiver, so none is reported here"
493        );
494        assert_eq!(110, reports[0].rtp_sequence_number);
495        assert_eq!(
496            10,
497            history.unreported(),
498            "the uncovered ten have no verdict"
499        );
500        assert!(history.is_empty(), "and are not kept");
501    }
502
503    /// A retransmission that keeps its transport-wide number takes the receiver's verdict; the
504    /// transmission it replaces is the loss that caused it, and stays one.
505    #[test]
506    fn a_transmission_superseded_under_the_same_number_is_reported_lost() {
507        let now = Instant::now();
508        let mut history = History::new();
509        history.add_outgoing(1, 100, true, 7, 1200, now);
510        history.add_outgoing(1, 100, true, 7, 1200, now + Duration::from_millis(40));
511
512        history.on_twcc_feedback(
513            now + Duration::from_millis(80),
514            Acknowledgement::received(7, None, Ecn::NotEct),
515        );
516
517        let reports = history.take_reports();
518        assert_eq!(
519            vec![false, true],
520            reports
521                .iter()
522                .map(|report| report.arrived)
523                .collect::<Vec<_>>()
524        );
525        assert_eq!(0, history.unreported());
526    }
527
528    /// A packet the receiver itself reports as not received is still a loss, once the next
529    /// feedback has not reported it received either.
530    #[test]
531    fn a_packet_reported_not_received_is_a_loss() {
532        let now = Instant::now();
533        let mut history = history_with_three_packets(now);
534
535        history.on_twcc_feedback(now, Acknowledgement::lost(0));
536        history.on_twcc_feedback(now, Acknowledgement::received(1, None, Ecn::NotEct));
537        history.on_twcc_feedback(now, Acknowledgement::received(2, None, Ecn::NotEct));
538
539        let arrived = |reports: Vec<PacketReport>| -> Vec<bool> {
540            reports.iter().map(|report| report.arrived).collect()
541        };
542        assert_eq!(vec![true, true], arrived(history.take_reports()));
543        assert_eq!(
544            vec![false],
545            arrived(history.take_reports()),
546            "the next feedback's turn"
547        );
548        assert_eq!(0, history.unreported());
549        assert_eq!(0, history.recovered());
550    }
551
552    /// A packet only overtaken on the path is reported as not received by the feedback that
553    /// covered the packets after it, and as received by the next. It is not a loss
554    /// (libwebrtc's `TransportFeedbackAdapter` keeps a lost packet "because it might be
555    /// reported as received by a later feedback"): the history holds a reported loss for one
556    /// more feedback, and reports the packet as received, without an arrival time for the
557    /// delay model, which reads reports in send order.
558    #[test]
559    fn a_packet_reported_lost_and_then_received_is_not_a_loss() {
560        let now = Instant::now();
561        let mut history = history_with_three_packets(now);
562
563        history.on_twcc_feedback(now, Acknowledgement::lost(0));
564        history.on_twcc_feedback(now, Acknowledgement::received(1, None, Ecn::NotEct));
565        assert_eq!(1, history.take_reports().len(), "1, and 0 held back");
566        history.on_twcc_feedback(
567            now,
568            Acknowledgement::received(0, Some(Duration::from_millis(50)), Ecn::NotEct),
569        );
570        history.on_twcc_feedback(now, Acknowledgement::received(2, None, Ecn::NotEct));
571        let reports = history.take_reports();
572        assert_eq!(2, reports.len());
573        assert!(reports.iter().all(|report| report.arrived), "{reports:?}");
574        assert_eq!(None, reports[0].arrival, "0 is out of send order now");
575        assert_eq!(1, history.recovered());
576    }
577
578    /// After a path was left, packets sent on the new one before the first that arrived over
579    /// it, and reported as not received, have no verdict: the path did not carry media yet
580    /// (the other end had not selected it). A packet lost after the first arrival is a loss.
581    #[test]
582    fn a_loss_before_anything_arrived_on_a_new_path_is_not_reported() {
583        let now = Instant::now();
584        let mut history = history_with_three_packets(now);
585        history.forget_sent();
586        // 10, 11: before the path carried anything. 12 arrives, 13 is lost, 14 arrives.
587        for sequence_number in 10..15u16 {
588            history.add_outgoing(1, 100 + sequence_number, true, sequence_number, 1200, now);
589        }
590        history.on_twcc_feedback(now, Acknowledgement::lost(10));
591        history.on_twcc_feedback(now, Acknowledgement::lost(11));
592        history.on_twcc_feedback(now, Acknowledgement::received(12, None, Ecn::NotEct));
593        history.on_twcc_feedback(now, Acknowledgement::lost(13));
594        history.on_twcc_feedback(now, Acknowledgement::received(14, None, Ecn::NotEct));
595        let verdicts = |reports: Vec<PacketReport>| -> Vec<(u16, bool)> {
596            reports
597                .iter()
598                .map(|report| (report.rtp_sequence_number, report.arrived))
599                .collect()
600        };
601        assert_eq!(
602            vec![(112, true), (114, true)],
603            verdicts(history.take_reports())
604        );
605        // The losses were held for one more feedback (they may only have been overtaken).
606        history.add_outgoing(1, 115, true, 15, 1200, now);
607        history.on_twcc_feedback(now, Acknowledgement::received(15, None, Ecn::NotEct));
608        assert_eq!(
609            vec![(113, false), (115, true)],
610            verdicts(history.take_reports()),
611            "10 and 11 have no verdict, 13 is a loss"
612        );
613        assert_eq!(2, history.before_the_path_carried());
614        assert!(history.is_empty());
615    }
616
617    /// Without a path change the first packets lost are losses as ever.
618    #[test]
619    fn a_loss_before_the_first_arrival_of_a_call_is_reported() {
620        let now = Instant::now();
621        let mut history = history_with_three_packets(now);
622        history.on_twcc_feedback(now, Acknowledgement::lost(0));
623        history.on_twcc_feedback(now, Acknowledgement::received(1, None, Ecn::NotEct));
624        history.take_reports();
625        history.on_twcc_feedback(now, Acknowledgement::received(2, None, Ecn::NotEct));
626        let reports = history.take_reports();
627        assert_eq!(
628            vec![false, true],
629            reports
630                .iter()
631                .map(|report| report.arrived)
632                .collect::<Vec<_>>()
633        );
634        assert_eq!(0, history.before_the_path_carried());
635    }
636
637    /// The feedback packet count is how a lost feedback packet is told from a quiet receiver
638    /// (section 3.1).
639    #[test]
640    fn a_gap_in_the_feedback_packet_count_is_a_lost_feedback_packet() {
641        let mut history = History::new();
642
643        assert_eq!(0, history.on_twcc_feedback_count(254), "the first one");
644        assert_eq!(0, history.on_twcc_feedback_count(255), "consecutive");
645        assert_eq!(
646            2,
647            history.on_twcc_feedback_count(2),
648            "0 and 1 are missing, across the wrap"
649        );
650        assert_eq!(
651            0,
652            history.on_twcc_feedback_count(1),
653            "a late one is not a gap"
654        );
655        assert_eq!(0, history.on_twcc_feedback_count(3));
656        assert_eq!(2, history.lost_feedback());
657    }
658
659    /// RFC 8888 names packets by the stream's own sequence number, so two streams can use the
660    /// same one and must not be confused.
661    #[test]
662    fn ccfb_feedback_matches_by_ssrc_and_sequence_number() {
663        let now = Instant::now();
664        let mut history = History::new();
665        history.add_outgoing(1, 500, false, 0, 1000, now);
666        history.add_outgoing(2, 500, false, 0, 1000, now);
667
668        history.on_ccfb_feedback(
669            now + Duration::from_millis(50),
670            2,
671            Acknowledgement::received(500, Some(Duration::from_millis(1)), Ecn::Ce),
672        );
673
674        // Stream 1's packet was sent first and no report block described it: it has no verdict,
675        // and is not a loss (draft-ietf-rmcat-gcc bug G2).
676        let reports = history.take_reports();
677        assert_eq!(1, reports.len());
678        assert_eq!(2, reports[0].ssrc);
679        assert!(reports[0].arrived, "stream 2's was acknowledged");
680        assert_eq!(Ecn::Ce, reports[0].ecn);
681    }
682
683    /// Feedback naming a stream that never sent that sequence number must not match another
684    /// stream that did. RFC 8888 numbers packets per stream, so the same sequence number is in
685    /// use on every stream at once — matching on it alone would attribute one stream's arrival to
686    /// another and corrupt both their delay estimates.
687    ///
688    /// Deterministic by construction: only stream 1 ever sent 500, so a lookup that ignores the
689    /// SSRC can only match stream 1's packet, and a correct one can only fail.
690    #[test]
691    fn ccfb_feedback_for_a_sequence_number_another_stream_sent_does_not_match() {
692        let now = Instant::now();
693        let mut history = History::new();
694        history.add_outgoing(1, 500, false, 0, 1000, now);
695
696        assert_eq!(
697            None,
698            history.on_ccfb_feedback(
699                now + Duration::from_millis(50),
700                2,
701                Acknowledgement::received(500, Some(Duration::from_millis(1)), Ecn::NotEct),
702            ),
703            "stream 2 never sent sequence 500"
704        );
705        assert!(
706            history.take_reports().is_empty(),
707            "and nothing was acknowledged, so stream 1's packet is still outstanding"
708        );
709    }
710
711    #[test]
712    fn nothing_is_reported_until_something_is_acknowledged() {
713        let now = Instant::now();
714        let mut history = history_with_three_packets(now);
715
716        assert!(
717            history.take_reports().is_empty(),
718            "sent but not yet acknowledged"
719        );
720        assert_eq!(3, history.len(), "and still tracked");
721    }
722
723    /// A packet reported once must not be reported again: congestion control would count it
724    /// twice, and a loss re-reported later looks like a reordered arrival.
725    #[test]
726    fn packets_are_reported_once() {
727        let now = Instant::now();
728        let mut history = history_with_three_packets(now);
729
730        history.on_twcc_feedback(now, Acknowledgement::lost(0));
731        history.on_twcc_feedback(now, Acknowledgement::received(1, None, Ecn::NotEct));
732        history.on_twcc_feedback(now, Acknowledgement::received(2, None, Ecn::NotEct));
733        // 1 and 2, then the loss of 0 a feedback later.
734        assert_eq!(2, history.take_reports().len());
735        assert_eq!(1, history.take_reports().len());
736        assert!(history.take_reports().is_empty());
737        assert!(history.is_empty(), "and released");
738    }
739
740    #[test]
741    fn later_feedback_reports_only_what_follows() {
742        let now = Instant::now();
743        let mut history = History::new();
744        history.add_outgoing(1, 100, true, 0, 1200, now);
745        history.add_outgoing(1, 101, true, 1, 1200, now);
746
747        history.on_twcc_feedback(now, Acknowledgement::received(0, None, Ecn::NotEct));
748        assert_eq!(1, history.take_reports().len());
749
750        history.on_twcc_feedback(now, Acknowledgement::received(1, None, Ecn::NotEct));
751        let reports = history.take_reports();
752        assert_eq!(1, reports.len());
753        assert_eq!(101, reports[0].rtp_sequence_number);
754    }
755
756    /// A packet reported as lost does not advance the reporting window on its own — otherwise a
757    /// long run of losses would flush packets that have not been heard about yet.
758    #[test]
759    fn a_loss_alone_does_not_advance_the_window() {
760        let now = Instant::now();
761        let mut history = history_with_three_packets(now);
762
763        history.on_twcc_feedback(now, Acknowledgement::lost(1));
764        assert!(
765            history.take_reports().is_empty(),
766            "nothing has been acknowledged as arrived"
767        );
768        assert_eq!(3, history.len());
769    }
770
771    /// The round trip is measured between two instants on *this* endpoint's clock, unlike the
772    /// arrival times, which are on the receiver's.
773    #[test]
774    fn the_round_trip_is_measured_locally() {
775        let now = Instant::now();
776        let mut history = History::new();
777        history.add_outgoing(1, 100, true, 0, 1200, now);
778
779        assert_eq!(
780            Some(Duration::from_millis(120)),
781            history.on_twcc_feedback(
782                now + Duration::from_millis(120),
783                Acknowledgement::received(0, Some(Duration::from_secs(9999)), Ecn::NotEct),
784            ),
785            "the receiver's arrival clock does not affect it"
786        );
787    }
788
789    /// Without pruning, an unacknowledged packet is never reported and never removed, so a lossy
790    /// path grows the history without bound.
791    /// A non-TWCC packet carries a meaningless `twcc_sequence_number` (whatever the caller
792    /// passed, typically 0) and was never entered into the TWCC index. Removing that key when it
793    /// is released evicts whichever *real* TWCC packet happens to hold it, and that packet's
794    /// feedback can then never match.
795    #[test]
796    fn releasing_a_non_twcc_packet_does_not_evict_a_twcc_packets_index_entry() {
797        let now = Instant::now();
798        let mut history = History::new();
799
800        // The non-TWCC packet is sent *first*, so reporting it does not sweep up the TWCC one:
801        // the reporting window runs to the highest arrived id, and anything below it is released
802        // regardless. Ordering this way isolates the index eviction from that.
803        history.add_outgoing(2, 200, false, 0, 1200, now);
804        // A real TWCC packet holding transport-wide sequence 0, sent after.
805        history.add_outgoing(1, 100, true, 0, 1200, now);
806
807        // Release the non-TWCC packet by reporting it.
808        history.on_ccfb_feedback(now, 2, Acknowledgement::received(200, None, Ecn::NotEct));
809        history.take_reports();
810
811        assert!(
812            history
813                .on_twcc_feedback(now, Acknowledgement::received(0, None, Ecn::NotEct))
814                .is_some(),
815            "the TWCC packet is still matchable by its transport-wide sequence number"
816        );
817    }
818
819    /// The same hazard on the pruning path.
820    #[test]
821    fn pruning_a_non_twcc_packet_does_not_evict_a_twcc_packets_index_entry() {
822        let now = Instant::now();
823        let mut history = History::new();
824
825        // Old, non-TWCC, carrying the default 0 it never registered.
826        history.add_outgoing(2, 200, false, 0, 1200, now);
827        // Recent, a real TWCC packet holding transport-wide sequence 0.
828        history.add_outgoing(1, 100, true, 0, 1200, now + Duration::from_secs(5));
829
830        history.prune_before(now + Duration::from_secs(1));
831
832        assert!(
833            history
834                .on_twcc_feedback(
835                    now + Duration::from_secs(5),
836                    Acknowledgement::received(0, None, Ecn::NotEct)
837                )
838                .is_some(),
839            "pruning the unrelated packet must not take the TWCC index entry with it"
840        );
841    }
842
843    /// An acknowledged packet that has not been reported yet must survive pruning, or the arrival
844    /// is lost and congestion control never hears about it.
845    #[test]
846    fn an_acknowledged_packet_is_not_pruned_before_it_is_reported() {
847        let now = Instant::now();
848        let mut history = History::new();
849        history.add_outgoing(1, 100, true, 0, 1200, now);
850
851        history.on_twcc_feedback(
852            now + Duration::from_millis(50),
853            Acknowledgement::received(0, None, Ecn::NotEct),
854        );
855
856        // Well past the cutoff, but it has been acknowledged and not yet collected.
857        history.prune_before(now + Duration::from_secs(30));
858
859        let reports = history.take_reports();
860        assert_eq!(1, reports.len(), "the arrival survived to be reported");
861        assert!(reports[0].arrived);
862    }
863
864    #[test]
865    fn old_unacknowledged_packets_are_pruned() {
866        let now = Instant::now();
867        let mut history = History::new();
868        history.add_outgoing(1, 100, true, 0, 1200, now);
869        history.add_outgoing(1, 101, true, 1, 1200, now + Duration::from_secs(5));
870
871        history.prune_before(now + Duration::from_secs(1));
872
873        assert_eq!(1, history.len(), "only the recent one survives");
874        assert_eq!(
875            None,
876            history.on_twcc_feedback(now, Acknowledgement::received(0, None, Ecn::NotEct)),
877            "and the pruned one is no longer matchable"
878        );
879    }
880}