Skip to main content

rtci_interceptor/rfc8888/
ecn.rs

1//! ECN initiation and failure detection for an RTP stream whose feedback is RFC 8888.
2//!
3//! RFC 8888 section 7: "When using ECN with RTP, the guidelines in Section 7.2 of [RFC6679]
4//! MUST be followed to initiate the use of ECN in an RTP session", section 7.3's ongoing use
5//! likewise, and "the guidance in Section 7.4 of [RFC6679] related to detecting failures MUST
6//! be followed, with the exception that the necessary information is retrieved from the RTCP
7//! Congestion Control Feedback Packets".
8//!
9//! [`EcnValidation`] is that sender-side procedure for one stream, sans-I/O: it is told of each
10//! packet sent ([`EcnValidation::on_send`], which answers whether the packet goes out ECT) and
11//! of each RFC 8888 report about one ([`EcnValidation::on_report`]).
12//!
13//! * **Initiation** (RFC 6679 section 7.2.1, the in-band method every implementation MUST
14//!   have): "an RTP sender SHALL mark a small fraction of its RTP traffic as ECT", "a minimum
15//!   of two packets with ECT markings per RTCP reporting interval" is RECOMMENDED, and it
16//!   "SHOULD NOT mark all RTP packets". Here one packet in [`PROBE_SPACING`], and one at least
17//!   every [`PROBE_INTERVAL`], never two in a row. On a unicast transport the initiation "MAY
18//!   [be treated] as provisionally successful if it receives [a report] indicating successful
19//!   receipt of the ECT-marked packets, with no negative indications": [`CONFIRMATIONS`]
20//!   probes reported received ECT (or CE) and none reported Not-ECT. It "is considered to have
21//!   failed" when the feedback shows the receiver "should have received multiple (>3)
22//!   ECT-marked RTP packets" and none arrived marked: here more than three probes reported
23//!   lost while none was reported received, or a probe reported received Not-ECT.
24//! * **Ongoing use** (section 7.3.1): after success the sender "SHOULD mark all the RTP data
25//!   packets it sends as ECT".
26//! * **Failures** (section 7.4): a path that clears the ECN field ("the ratio [...] has become
27//!   all not-ECT, or has substantially changed towards not-ECT", section 7.4.2) stops the
28//!   marking: more than a quarter of a window of [`WINDOW`] reported ECT packets arrived
29//!   Not-ECT. "A sender that detects high packet loss rates for ECT-marked packets SHOULD
30//!   immediately switch to sending packets as not-ECT to determine if the losses are
31//!   potentially due to the ECT markings. If the losses disappear when the ECT-marking is
32//!   discontinued, the RTP sender should go back to initiation procedures": half a window lost
33//!   switches to Not-ECT for a window; if the loss falls under a quarter the stream initiates
34//!   again, else (the loss is the path's, not ECN's) it resumes marking. After a failed
35//!   initiation the sender "periodically [retries] the ECN initiation" (the first option of
36//!   section 7.4.1) every [`DEFAULT_RETRY_AFTER`], and "if multiple initiations have been successful, but
37//!   the following full usage of ECN has resulted in the fallback procedures, then disabling
38//!   of the ECN support is RECOMMENDED": the second such fallback ends ECN for the stream.
39//!
40//! RTCP is never marked (section 7.2: "SHALL NOT ECT mark their RTCP traffic"); that is the
41//! caller's part, as is choosing the codepoint (ECT(1) for L4S, RFC 9331).
42
43use rtcp::transport_feedbacks::cc_feedback_report::Ecn;
44use rtcp::transport_feedbacks::ecn_feedback::EcnCounters;
45use std::collections::BTreeMap;
46use std::time::{Duration, Instant};
47
48/// During initiation one packet in this many is a probe sent ECT.
49pub const PROBE_SPACING: u32 = 10;
50/// During initiation a probe is sent at least this often (given an unmarked packet since the
51/// last one): two per RTCP reporting interval at the shortest regular interval RFC 3550
52/// section 6.2 allows a reduced-minimum sender (360 / session kbit/s seconds) is met for any
53/// session above 720 kbit/s by the spacing, and below by this.
54pub const PROBE_INTERVAL: Duration = Duration::from_millis(500);
55/// Probes reported received with an ECN-capable marking that make the initiation succeed.
56pub const CONFIRMATIONS: u32 = 2;
57/// Probes reported lost, none received, that make the initiation fail (RFC 6679 section 7.2.1:
58/// "multiple (>3)").
59pub const PROBES_LOST_TO_FAIL: u32 = 4;
60/// Reported packets the failure checks of ongoing use are made over.
61pub const WINDOW: u32 = 32;
62/// How long after a failed initiation the next one starts (RFC 6679 section 7.4.1 option 1).
63pub const DEFAULT_RETRY_AFTER: Duration = Duration::from_secs(60);
64/// Fallbacks from ongoing use, each confirmed as ECN's doing, after which ECN stays off.
65pub const FALLBACKS_TO_DISABLE: u32 = 2;
66/// How long after the start of an initiation a provisional success is watched for other
67/// receivers (RFC 6679 section 7.2.1: "three RTCP reporting intervals from the time the ECN
68/// initiation started"): three of RTP/AVP's 5 s minimum interval, the longest regular
69/// interval this engine computes without a configured `trr-int`.
70pub const PROVISIONAL_MONITOR: Duration = Duration::from_secs(15);
71/// One RTCP reporting interval as [`PROVISIONAL_MONITOR`] counts three of them: the complete
72/// interval without a change of the group membership that RFC 6679 section 7.2.1 asks for
73/// before the membership is stable.
74pub const REPORTING_INTERVAL: Duration = Duration::from_secs(5);
75/// The most participants (RTCP CNAMEs) a stream's validation follows; further ones are not
76/// waited for.
77const MAX_PARTICIPANTS: usize = 16;
78
79/// Sent packets remembered, by sequence number, to match reports with how each was sent.
80const HISTORY: usize = 2048;
81
82/// Where a stream is in RFC 6679's procedure.
83#[derive(Debug, Clone, Copy, PartialEq, Eq)]
84pub enum EcnState {
85    /// Section 7.2.1: a fraction of the packets are probes sent ECT.
86    Initiating,
87    /// Section 7.3.1: every packet is sent ECT.
88    Active,
89    /// Section 7.4.1: ECT-marked packets were lost at a high rate; packets go out Not-ECT to
90    /// see whether the loss goes with the marking.
91    Fallback,
92    /// The path does not carry ECN; nothing is marked until `retry_at`.
93    Failed {
94        /// When the next initiation starts.
95        retry_at: Instant,
96    },
97    /// ECN is off for the stream for good (section 7.4.1).
98    Disabled,
99}
100
101/// Which ECT codepoint a receiver asks the sender to use: the `ect=` parameter of its
102/// `a=ecn-capable-rtp` (RFC 6679 section 6.1). Left out, the sender uses ECT(0).
103#[derive(Debug, Clone, Copy, PartialEq, Eq)]
104pub enum EctPreference {
105    /// `ect=0`.
106    Ect0,
107    /// `ect=1`.
108    Ect1,
109    /// `ect=random`: the sender picks ECT(0) or ECT(1) at random for each packet.
110    Random,
111}
112
113impl EctPreference {
114    /// The value of an `ect=` parameter (`0`, `1` or `random`, any case); `None` for any
115    /// other, which RFC 6679 section 6.1 has the receiver of the description ignore.
116    pub fn from_sdp(value: &str) -> Option<Self> {
117        match value.trim().to_ascii_lowercase().as_str() {
118            "0" => Some(Self::Ect0),
119            "1" => Some(Self::Ect1),
120            "random" => Some(Self::Random),
121            _ => None,
122        }
123    }
124}
125
126/// Which ECT codepoint a stream that marks sends.
127#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
128pub enum EcnMarking {
129    /// RFC 6679 section 7.3.1: ECT(0), unless the receiver asked for ECT(1) or a random
130    /// choice ([`EctPreference`]).
131    #[default]
132    Rfc6679,
133    /// ECT(1), the L4S identifier (RFC 9331), whatever the receiver asked: what browsers that
134    /// send L4S do.
135    L4s,
136}
137
138impl EcnMarking {
139    /// The codepoint the next packet goes out with, given the receiver's preference;
140    /// `coin` is a random bit, used for [`EctPreference::Random`].
141    pub fn codepoint(self, preference: Option<EctPreference>, coin: bool) -> shared::EcnCodepoint {
142        match (self, preference) {
143            (Self::L4s, _) | (Self::Rfc6679, Some(EctPreference::Ect1)) => {
144                shared::EcnCodepoint::Ect1
145            }
146            (Self::Rfc6679, Some(EctPreference::Random)) if coin => shared::EcnCodepoint::Ect1,
147            _ => shared::EcnCodepoint::Ect0,
148        }
149    }
150}
151
152/// How a stream starts using ECN.
153#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
154pub enum EcnInitiation {
155    /// RFC 6679 section 7.2.1: probes, then every packet once feedback confirmed them (the
156    /// method every implementation MUST have).
157    #[default]
158    RtpAndRtcp,
159    /// RFC 6679 section 7.2.3, leap of faith: every packet is sent ECT from the first, as
160    /// browsers that implement L4S do. Failure detection (section 7.4) still applies. The RFC
161    /// allows it only for sessions that accept its limitations (the first packets may be lost
162    /// on a path that drops ECT traffic).
163    LeapOfFaith,
164}
165
166impl EcnInitiation {
167    /// RFC 6679 section 7.2: "all participants in an RTP session MUST use the same ECN
168    /// initiation method". Given each section's transport and the method its negotiation
169    /// gave, the method each section's streams use: the first method negotiated on the
170    /// transport, for every section on it that uses ECN at all (bundled sections share one
171    /// RTP session, RFC 9143). A section without ECN stays without.
172    pub fn one_per_transport<K: PartialEq + Copy>(
173        sections: &[(K, Option<EcnInitiation>)],
174    ) -> Vec<Option<EcnInitiation>> {
175        sections
176            .iter()
177            .map(|(transport, method)| {
178                method.and_then(|_| {
179                    sections
180                        .iter()
181                        .find(|(other, m)| other == transport && m.is_some())
182                        .and_then(|(_, m)| *m)
183                })
184            })
185            .collect()
186    }
187}
188
189/// An ECN failure a stream's validation detected (RFC 6679 sections 7.2.1 and 7.4.2: detected
190/// failures and erroneous behaviour "should" be logged "to enable follow up"). Each is logged
191/// and kept for the application ([`EcnValidation::take_failures`]).
192#[derive(Debug, Clone, Copy, PartialEq, Eq)]
193#[non_exhaustive]
194pub enum EcnFailure {
195    /// Initiation failed: an ECT probe was reported arriving Not-ECT.
196    ProbeArrivedNotEct,
197    /// Initiation failed: no ECT probe arrived.
198    NoProbeArrived,
199    /// Initiation failed: the path clears the ECN field.
200    FieldCleared,
201    /// Initiation failed: the receiver's counters counted the ECT probes as Not-ECT.
202    ProbesCountedNotEct,
203    /// Initiation failed: a receiver reported more than three probes in a reception report
204    /// without an ECN report (section 7.2.1).
205    NoEcnReport,
206    /// Leap of faith failed: two receiver reports in a row showed no reception of the stream
207    /// (section 7.2.3).
208    NoReception,
209    /// After initiation, ECT packets were lost where Not-ECT ones were not (section 7.4.2):
210    /// the stream falls back and initiates again, or, `disabled`, ECN stays off for it.
211    EctLost {
212        /// Whether ECN is now off for the stream.
213        disabled: bool,
214    },
215}
216
217impl EcnFailure {
218    /// Whether this ends an initiation (section 7.2.1), as against a failure after one.
219    pub fn is_initiation_failure(&self) -> bool {
220        !matches!(self, EcnFailure::EctLost { .. })
221    }
222}
223
224impl std::fmt::Display for EcnFailure {
225    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
226        f.write_str(match self {
227            EcnFailure::ProbeArrivedNotEct => "an ECT probe arrived Not-ECT",
228            EcnFailure::NoProbeArrived => "no ECT probe arrived",
229            EcnFailure::FieldCleared => "the path clears the ECN field",
230            EcnFailure::ProbesCountedNotEct => "ECT probes were counted Not-ECT",
231            EcnFailure::NoEcnReport => {
232                "a receiver reported more than three probes without an ECN report"
233            }
234            EcnFailure::NoReception => "two receiver reports in a row showed no reception",
235            EcnFailure::EctLost { disabled: true } => {
236                "ECT packets were lost again; ECN off for the stream"
237            }
238            EcnFailure::EctLost { disabled: false } => "ECT packets were lost; initiating again",
239        })
240    }
241}
242
243/// At most this many failures are kept for the application.
244const MAX_KEPT_FAILURES: usize = 16;
245
246#[derive(Debug, Clone, Copy, Default)]
247struct Sent {
248    sequence_number: u16,
249    /// Whether this slot describes a packet at all.
250    known: bool,
251    marked: bool,
252    /// Reported so far: received (true), lost (false), not yet (`None`).
253    reported: Option<bool>,
254}
255
256/// Counts over one window of reported packets.
257#[derive(Debug, Clone, Copy, Default)]
258struct Window {
259    reported: u32,
260    lost: u32,
261    bleached: u32,
262}
263
264/// The participants of a session with more than one RTCP CNAME (RFC 6679 section 7.2.1): "An
265/// RTP sender shall consider the group membership to be stable after it has been in the
266/// session and sending ECT-marked probe packets for at least three RTCP reporting intervals
267/// ... and when a complete RTCP reporting interval has passed without changes to the group
268/// membership. ECN initiation is considered successful when the group membership is stable
269/// and all known participants have sent one or more RTCP ECN feedback packets or RTCP XR ECN
270/// Summary Reports indicating correct receipt of the ECT-marked RTP packets".
271#[derive(Debug, Clone, Default)]
272struct Group {
273    /// Each participant's CNAME and whether it confirmed the current initiation's probes.
274    members: BTreeMap<String, bool>,
275    /// When the membership last changed; `None`: not since the stream's validation began.
276    changed_at: Option<Instant>,
277}
278
279/// RFC 6679 sections 7.2-7.4 for one RTP stream, fed from RFC 8888 reports. See the module
280/// documentation.
281#[derive(Debug, Clone)]
282pub struct EcnValidation {
283    state: EcnState,
284    retry_after: Duration,
285    since_probe: u32,
286    last_probe: Option<Instant>,
287    history: Box<[Sent]>,
288    probes_confirmed: u32,
289    probes_lost: u32,
290    window: Window,
291    /// The loss of the window that sent the stream into [`EcnState::Fallback`].
292    fallback_from: u32,
293    fallbacks: u32,
294    /// The last RFC 6679 counters each reporter gave (by its RTCP CNAME, `None` when it is not
295    /// known), with the extended highest sequence number they relate to
296    /// ([`EcnValidation::on_counters_from`]): each receiver counts on its own.
297    last_counters: Vec<(Option<String>, u32, EcnCounters)>,
298    /// When the current initiation sent its first probe.
299    initiated_at: Option<Instant>,
300    /// The success of the initiation is provisional until then (section 7.2.1).
301    provisional_until: Option<Instant>,
302    /// The RTCP CNAME of the receiver whose reports confirmed the probes.
303    receiver_cname: Option<String>,
304    /// More than one RTCP CNAME seen: the session is a group, and initiation follows the full
305    /// procedure of section 7.2.1 instead of the unicast optimisation.
306    group: Option<Group>,
307    /// Failures detected and not taken yet.
308    failures: Vec<EcnFailure>,
309    /// Marking from the first packet without probes (section 7.2.3), until reception is seen.
310    leap_of_faith: bool,
311    /// Receiver reports in a row that showed no reception of the stream.
312    reports_without_reception: u32,
313}
314
315impl Default for EcnValidation {
316    fn default() -> Self {
317        Self::new(EcnInitiation::default())
318    }
319}
320
321impl EcnValidation {
322    /// A stream about to send its first packet with ECN negotiated.
323    pub fn new(initiation: EcnInitiation) -> Self {
324        Self {
325            state: match initiation {
326                EcnInitiation::RtpAndRtcp => EcnState::Initiating,
327                EcnInitiation::LeapOfFaith => EcnState::Active,
328            },
329            retry_after: DEFAULT_RETRY_AFTER,
330            since_probe: PROBE_SPACING,
331            last_probe: None,
332            history: vec![Sent::default(); HISTORY].into_boxed_slice(),
333            probes_confirmed: 0,
334            probes_lost: 0,
335            window: Window::default(),
336            fallback_from: 0,
337            fallbacks: 0,
338            last_counters: Vec::new(),
339            initiated_at: None,
340            provisional_until: None,
341            receiver_cname: None,
342            group: None,
343            failures: Vec::new(),
344            leap_of_faith: initiation == EcnInitiation::LeapOfFaith,
345            reports_without_reception: 0,
346        }
347    }
348
349    /// How long after a failed initiation the next one starts ([`DEFAULT_RETRY_AFTER`]).
350    pub fn with_retry_after(mut self, retry_after: Duration) -> Self {
351        self.retry_after = retry_after;
352        self
353    }
354
355    /// Where the stream is in the procedure.
356    pub fn state(&self) -> EcnState {
357        self.state
358    }
359
360    /// Whether a packet of the stream that is not one of its own numbered packets (an RTX
361    /// retransmission, say) goes out ECT: only in ongoing use, so probes are the stream's own
362    /// packets, whose reports name them.
363    pub fn marks_all(&self) -> bool {
364        self.state == EcnState::Active
365    }
366
367    /// Whether the packet `sequence_number` was sent ECT, as far as the history still knows.
368    pub fn was_marked(&self, sequence_number: u16) -> bool {
369        let slot = &self.history[usize::from(sequence_number) % HISTORY];
370        slot.known && slot.sequence_number == sequence_number && slot.marked
371    }
372
373    /// A packet of the stream is sent at `now`: whether it goes out ECT.
374    pub fn on_send(&mut self, now: Instant, sequence_number: u16) -> bool {
375        if let EcnState::Failed { retry_at } = self.state
376            && now >= retry_at
377        {
378            self.initiate();
379        }
380        let marked = match self.state {
381            EcnState::Initiating => {
382                let due = self.since_probe + 1 >= PROBE_SPACING
383                    || (self.since_probe >= 1
384                        && self
385                            .last_probe
386                            .is_none_or(|at| now.saturating_duration_since(at) >= PROBE_INTERVAL));
387                if due {
388                    self.since_probe = 0;
389                    self.last_probe = Some(now);
390                    self.initiated_at.get_or_insert(now);
391                } else {
392                    self.since_probe += 1;
393                }
394                if self.group_success(now) { true } else { due }
395            }
396            EcnState::Active => true,
397            EcnState::Fallback | EcnState::Failed { .. } | EcnState::Disabled => false,
398        };
399        self.history[usize::from(sequence_number) % HISTORY] = Sent {
400            sequence_number,
401            known: true,
402            marked,
403            reported: None,
404        };
405        marked
406    }
407
408    /// An RFC 8888 report about the packet `sequence_number` arrived at `now`: whether it was
409    /// received, and if so the ECN field it arrived with. The reporter is not known
410    /// ([`on_report_from`](Self::on_report_from)).
411    pub fn on_report(&mut self, now: Instant, sequence_number: u16, received: bool, ecn: Ecn) {
412        self.on_report_from(now, None, sequence_number, received, ecn);
413    }
414
415    /// [`on_report`](Self::on_report) from the participant whose RTCP CNAME is `reporter`. In a
416    /// group (more than one CNAME seen) a probe reported arriving ECT or CE confirms the
417    /// initiation for that participant, even when another reported the packet first.
418    pub fn on_report_from(
419        &mut self,
420        now: Instant,
421        reporter: Option<&str>,
422        sequence_number: u16,
423        received: bool,
424        ecn: Ecn,
425    ) {
426        let slot = &mut self.history[usize::from(sequence_number) % HISTORY];
427        if !slot.known || slot.sequence_number != sequence_number {
428            return;
429        }
430        let ecn_capable = matches!(ecn, Ecn::Ect0 | Ecn::Ect1 | Ecn::Ce);
431        if self.state == EcnState::Initiating && slot.marked && received && ecn_capable {
432            self.confirm(now, reporter);
433        }
434        let slot = &mut self.history[usize::from(sequence_number) % HISTORY];
435        // Each packet counts once; a loss reported and then undone by a later report (the
436        // packet was late) is taken back.
437        let undo_loss = match slot.reported {
438            Some(true) => return,
439            Some(false) if !received => return,
440            Some(false) => true,
441            None => false,
442        };
443        slot.reported = Some(received);
444        let marked = slot.marked;
445
446        match self.state {
447            EcnState::Initiating if marked => {
448                if undo_loss {
449                    self.probes_lost = self.probes_lost.saturating_sub(1);
450                }
451                if !received {
452                    self.probes_lost += 1;
453                } else if ecn_capable {
454                    self.probes_confirmed += 1;
455                } else {
456                    // A negative indication: the path cleared the ECN field.
457                    self.fail(now, EcnFailure::ProbeArrivedNotEct);
458                    return;
459                }
460                if self.probes_confirmed == 0 && self.probes_lost >= PROBES_LOST_TO_FAIL {
461                    self.fail(now, EcnFailure::NoProbeArrived);
462                } else if self.group.is_none() && self.probes_confirmed >= CONFIRMATIONS {
463                    self.provisional_success(now);
464                } else {
465                    self.group_success(now);
466                }
467            }
468            EcnState::Active if marked => {
469                self.count(undo_loss, received, !ecn_capable);
470                if self.window.bleached * 4 > WINDOW {
471                    self.fail(now, EcnFailure::FieldCleared);
472                } else if self.window.lost * 2 >= WINDOW {
473                    log::debug!("ECN: high loss of ECT packets; sending Not-ECT to compare");
474                    self.state = EcnState::Fallback;
475                    self.fallback_from = self.window.lost;
476                    self.window = Window::default();
477                } else if self.window.reported >= WINDOW {
478                    self.window = Window::default();
479                }
480            }
481            EcnState::Fallback if !marked => {
482                self.count(undo_loss, received, false);
483                if self.window.reported >= WINDOW {
484                    if self.window.lost * 4 < WINDOW && self.window.lost * 2 < self.fallback_from {
485                        // The loss went with the marking.
486                        self.fallbacks += 1;
487                        if self.fallbacks >= FALLBACKS_TO_DISABLE {
488                            self.record(EcnFailure::EctLost { disabled: true });
489                            self.state = EcnState::Disabled;
490                        } else {
491                            self.record(EcnFailure::EctLost { disabled: false });
492                            self.initiate();
493                        }
494                    } else {
495                        // Not-ECT packets were lost as much: the path's loss, not ECN's.
496                        self.state = EcnState::Active;
497                        self.window = Window::default();
498                    }
499                }
500            }
501            _ => {}
502        }
503    }
504
505    /// An RFC 6679 report about the stream arrived at `now`: the receiver's cumulative ECN
506    /// counters (an RTCP ECN Feedback packet, section 5.1, or an XR ECN Summary Report,
507    /// section 5.2) and the extended highest sequence number they relate to (the feedback
508    /// packet's, or the reception report's in the same compound packet). The procedure is the
509    /// one [`on_report`](Self::on_report) runs, on what changed since the last report: the
510    /// packets sent up to the new highest sequence number, how many went out ECT, and how many
511    /// the receiver counted ECT or CE, not-ECT, lost and duplicated (section 7.4.2).
512    ///
513    /// * Initiating: ECT or CE counts confirm probes; not-ECT counts beyond the unmarked
514    ///   packets sent (and the duplicates) are a negative indication; more than three probes
515    ///   sent with no ECT counted is a failure (section 7.2.1).
516    /// * Ongoing use: each packet sent ECT is reported; the not-ECT count beyond duplicates is
517    ///   bleaching, the lost count is loss; the thresholds are those of per-packet reports.
518    pub fn on_counters(&mut self, now: Instant, extended_highest: u32, counters: EcnCounters) {
519        self.on_counters_from(now, None, extended_highest, counters);
520    }
521
522    /// [`on_counters`](Self::on_counters) from the participant whose RTCP CNAME is `reporter`:
523    /// its counters are compared with its own last ones, and in a group, ECT or CE counted with
524    /// nothing cleared confirms the initiation for it.
525    pub fn on_counters_from(
526        &mut self,
527        now: Instant,
528        reporter: Option<&str>,
529        extended_highest: u32,
530        counters: EcnCounters,
531    ) {
532        let known = self
533            .last_counters
534            .iter()
535            .position(|(from, _, _)| from.as_deref() == reporter);
536        let (previous_highest, previous) = match known {
537            Some(index) => (self.last_counters[index].1, self.last_counters[index].2),
538            None => (
539                extended_highest.wrapping_sub(self.known_since(extended_highest)),
540                EcnCounters::default(),
541            ),
542        };
543        // An older report than the last one says nothing new.
544        let span = extended_highest.wrapping_sub(previous_highest);
545        if span > 0x8000_0000 {
546            return;
547        }
548        match known {
549            Some(index) => {
550                self.last_counters[index].1 = extended_highest;
551                self.last_counters[index].2 = counters;
552            }
553            None => {
554                if self.last_counters.len() >= MAX_PARTICIPANTS {
555                    self.last_counters.remove(0);
556                }
557                self.last_counters
558                    .push((reporter.map(str::to_owned), extended_highest, counters));
559            }
560        }
561        if span == 0 && counters == previous {
562            return;
563        }
564        let ect = u64::from(counters.ect0.wrapping_sub(previous.ect0))
565            + u64::from(counters.ect1.wrapping_sub(previous.ect1))
566            + u64::from(counters.ce.wrapping_sub(previous.ce));
567        let not_ect = u64::from(counters.not_ect.wrapping_sub(previous.not_ect));
568        let duplicates = u64::from(counters.duplicates.wrapping_sub(previous.duplicates));
569        // The loss counter may fall (late packets) between reports.
570        let lost = i64::from(counters.lost.wrapping_sub(previous.lost) as i16).max(0) as u64;
571
572        // What went out in (previous_highest, extended_highest], as far as the history knows.
573        let (mut marked, mut unmarked) = (0u64, 0u64);
574        let first = previous_highest.wrapping_add(1);
575        for offset in 0..span.min(HISTORY as u32) {
576            let sequence_number = first.wrapping_add(offset) as u16;
577            let slot = &self.history[usize::from(sequence_number) % HISTORY];
578            if slot.known && slot.sequence_number == sequence_number {
579                if slot.marked {
580                    marked += 1;
581                } else {
582                    unmarked += 1;
583                }
584            }
585        }
586        let bleached = not_ect.saturating_sub(unmarked + duplicates);
587
588        match self.state {
589            EcnState::Initiating => {
590                if bleached > 0 && marked > 0 {
591                    self.fail(now, EcnFailure::ProbesCountedNotEct);
592                    return;
593                }
594                self.probes_confirmed += ect.min(u64::from(u32::MAX)) as u32;
595                if ect == 0 {
596                    self.probes_lost += marked as u32;
597                } else if bleached == 0 {
598                    self.confirm(now, reporter);
599                }
600                if self.probes_confirmed == 0 && self.probes_lost >= PROBES_LOST_TO_FAIL {
601                    self.fail(now, EcnFailure::NoProbeArrived);
602                } else if self.group.is_none()
603                    && self.probes_confirmed >= CONFIRMATIONS
604                    && bleached == 0
605                {
606                    self.provisional_success(now);
607                } else {
608                    self.group_success(now);
609                }
610            }
611            EcnState::Active => {
612                self.window.reported += marked as u32;
613                self.window.lost += lost.min(marked) as u32;
614                self.window.bleached += bleached.min(marked) as u32;
615                if self.window.bleached * 4 > WINDOW {
616                    self.fail(now, EcnFailure::FieldCleared);
617                } else if self.window.lost * 2 >= WINDOW {
618                    log::debug!("ECN: high loss of ECT packets; sending Not-ECT to compare");
619                    self.state = EcnState::Fallback;
620                    self.fallback_from = self.window.lost;
621                    self.window = Window::default();
622                } else if self.window.reported >= WINDOW {
623                    self.window = Window::default();
624                }
625            }
626            EcnState::Fallback => {
627                self.window.reported += unmarked as u32;
628                self.window.lost += lost.min(unmarked) as u32;
629                if self.window.reported >= WINDOW {
630                    if self.window.lost * 4 < WINDOW && self.window.lost * 2 < self.fallback_from {
631                        self.fallbacks += 1;
632                        if self.fallbacks >= FALLBACKS_TO_DISABLE {
633                            self.record(EcnFailure::EctLost { disabled: true });
634                            self.state = EcnState::Disabled;
635                        } else {
636                            self.record(EcnFailure::EctLost { disabled: false });
637                            self.initiate();
638                        }
639                    } else {
640                        self.state = EcnState::Active;
641                        self.window = Window::default();
642                    }
643                }
644            }
645            EcnState::Failed { .. } | EcnState::Disabled => {}
646        }
647    }
648
649    /// How many sequence numbers before `extended_highest` the history holds sent packets
650    /// for: the span the first RFC 6679 report covers.
651    fn known_since(&self, extended_highest: u32) -> u32 {
652        let mut span = 0u32;
653        while span < HISTORY as u32 {
654            let sequence_number = extended_highest.wrapping_sub(span) as u16;
655            let slot = &self.history[usize::from(sequence_number) % HISTORY];
656            if !(slot.known && slot.sequence_number == sequence_number) {
657                break;
658            }
659            span += 1;
660        }
661        span
662    }
663
664    fn count(&mut self, undo_loss: bool, received: bool, bleached: bool) {
665        if undo_loss {
666            self.window.lost = self.window.lost.saturating_sub(1);
667        } else {
668            self.window.reported += 1;
669        }
670        if !received {
671            self.window.lost += 1;
672        } else if bleached {
673            self.window.bleached += 1;
674        }
675    }
676
677    /// The probes were confirmed by one receiver: every packet is marked from now on, while
678    /// the session is watched for other receivers (section 7.2.1's optimisation for a
679    /// unicast peer).
680    fn provisional_success(&mut self, now: Instant) {
681        self.state = EcnState::Active;
682        self.window = Window::default();
683        let started = self.initiated_at.unwrap_or(now);
684        self.provisional_until = Some(started + PROVISIONAL_MONITOR);
685    }
686
687    /// RFC 6679 section 7.2.1: a source of the session named its RTCP CNAME at `now`. The
688    /// first one is the receiver the probes are confirmed by (the unicast optimisation).
689    /// Another CNAME makes the session a group: while the success is provisional "the sender
690    /// MUST fallback to only ECT-marking a small fraction of its RTP packets, while it
691    /// determines if ECN can be supported following the full procedure" ([`Group`]), and an
692    /// initiation in progress follows the full procedure from then on. Each new CNAME is a
693    /// change of the membership.
694    pub fn on_remote_cname(&mut self, now: Instant, cname: &str) {
695        if self.group.is_none() {
696            match &self.receiver_cname {
697                None => {
698                    self.receiver_cname = Some(cname.to_owned());
699                    return;
700                }
701                Some(known) if known == cname => return,
702                Some(_) => {}
703            }
704            let provisional = self.state == EcnState::Active
705                && self.provisional_until.is_some_and(|until| now < until);
706            let mut group = Group::default();
707            if let Some(first) = &self.receiver_cname {
708                group.members.insert(first.clone(), false);
709            }
710            self.group = Some(group);
711            if provisional {
712                log::info!(
713                    "ECN: another RTCP CNAME during a provisional success, probing again \
714                     (RFC 6679 section 7.2.1)"
715                );
716                self.initiate();
717            }
718        }
719        let Some(group) = self.group.as_mut() else {
720            return;
721        };
722        if group.members.contains_key(cname) || group.members.len() >= MAX_PARTICIPANTS {
723            return;
724        }
725        group.members.insert(cname.to_owned(), false);
726        group.changed_at = Some(now);
727    }
728
729    /// A validation that already knows the session's RTCP CNAMEs (named before the stream
730    /// started marking): more than one makes it a group from the start.
731    pub fn with_receiver_cnames<'a>(mut self, cnames: impl IntoIterator<Item = &'a str>) -> Self {
732        for cname in cnames {
733            if self.receiver_cname.is_none() {
734                self.receiver_cname = Some(cname.to_owned());
735                continue;
736            }
737            let group = self.group.get_or_insert_with(|| {
738                let mut group = Group::default();
739                if let Some(first) = &self.receiver_cname {
740                    group.members.insert(first.clone(), false);
741                }
742                group
743            });
744            if group.members.len() < MAX_PARTICIPANTS {
745                group.members.insert(cname.to_owned(), false);
746            }
747        }
748        self
749    }
750
751    /// Whether more than one RTCP CNAME has been seen, so that initiation follows the full
752    /// procedure of section 7.2.1.
753    pub fn is_group(&self) -> bool {
754        self.group.is_some()
755    }
756
757    /// In a group, `reporter` confirmed the probes of the current initiation. A reporter that
758    /// named no CNAME yet joins the membership with it.
759    fn confirm(&mut self, now: Instant, reporter: Option<&str>) {
760        let (Some(group), Some(reporter)) = (self.group.as_mut(), reporter) else {
761            return;
762        };
763        if let Some(confirmed) = group.members.get_mut(reporter) {
764            *confirmed = true;
765        } else if group.members.len() < MAX_PARTICIPANTS {
766            group.members.insert(reporter.to_owned(), true);
767            group.changed_at = Some(now);
768        }
769    }
770
771    /// RFC 6679 section 7.2.1, the full procedure: in a group, the initiation succeeds once
772    /// the stream has sent probes for three reporting intervals, a complete interval has
773    /// passed without a change of membership, and every participant confirmed the probes.
774    /// Every packet is marked from then on (section 7.3.1).
775    fn group_success(&mut self, now: Instant) -> bool {
776        let (Some(group), EcnState::Initiating, Some(started)) =
777            (&self.group, self.state, self.initiated_at)
778        else {
779            return false;
780        };
781        let stable_since = group
782            .changed_at
783            .map_or(started, |changed| changed.max(started));
784        let success = now >= started + PROVISIONAL_MONITOR
785            && now >= stable_since + REPORTING_INTERVAL
786            && !group.members.is_empty()
787            && group.members.values().all(|confirmed| *confirmed);
788        if success {
789            self.state = EcnState::Active;
790            self.window = Window::default();
791            self.provisional_until = None;
792        }
793        success
794    }
795
796    /// RFC 6679 section 7.2.1: "ECN initiation is considered to have failed at the instant
797    /// the initiating RTP sender received an RTCP packet that doesn't contain an RTCP ECN
798    /// Feedback Report or ECN Summary Report from any RTP session participant that has an
799    /// RTCP RR with an extended RTP sequence number field that indicates that it should have
800    /// received multiple (>3) ECT-marked RTP packets." `extended_highest` is that field of a
801    /// reception report about the stream in a compound packet without an ECN report about it.
802    pub fn on_reception_report_without_ecn(&mut self, now: Instant, extended_highest: u32) {
803        if self.state != EcnState::Initiating {
804            return;
805        }
806        let highest = extended_highest as u16;
807        let due = self
808            .history
809            .iter()
810            .filter(|sent| {
811                sent.known && sent.marked && {
812                    // At or before `highest`, within the history's reach.
813                    let behind = highest.wrapping_sub(sent.sequence_number);
814                    usize::from(behind) < HISTORY
815                }
816            })
817            .count();
818        if due > 3 {
819            self.fail(now, EcnFailure::NoEcnReport);
820        }
821    }
822
823    /// RFC 6679 section 7.2.3, leap of faith: a receiver report (SR or RR) arrived that has no
824    /// report block about the stream, or one showing that nothing was received. A path with an
825    /// ECN-blocking middlebox shows that way; but "a receiver might generate its first RTCP
826    /// packet ... before it has had chance to receive any data packets", so "a sender that
827    /// receives an RTCP SR/RR packet indicating lack of reception by a receiver SHOULD ...
828    /// wait for a second RTCP report from that receiver": the second such report in a row
829    /// ends the marking. Nothing changes once reception was reported, outside the leap of
830    /// faith, or before a marked packet was sent.
831    pub fn on_report_without_reception(&mut self, now: Instant) {
832        if !self.leap_of_faith
833            || self.state != EcnState::Active
834            || !self.history.iter().any(|sent| sent.known && sent.marked)
835        {
836            return;
837        }
838        self.reports_without_reception += 1;
839        if self.reports_without_reception >= 2 {
840            self.leap_of_faith = false;
841            self.fail(now, EcnFailure::NoReception);
842        }
843    }
844
845    /// A receiver report showed reception of the stream: the path carries its ECT packets.
846    pub fn on_reception_reported(&mut self) {
847        self.reports_without_reception = 0;
848        self.leap_of_faith = false;
849    }
850
851    /// A validation that knows the receiver by its RTCP CNAME already (named before the
852    /// stream started marking).
853    pub fn with_receiver_cname(mut self, cname: &str) -> Self {
854        self.receiver_cname = Some(cname.to_owned());
855        self
856    }
857
858    /// Whether the success of the initiation is still provisional at `now`.
859    pub fn is_provisional(&self, now: Instant) -> bool {
860        self.state == EcnState::Active && self.provisional_until.is_some_and(|until| now < until)
861    }
862
863    fn initiate(&mut self) {
864        if let Some(group) = self.group.as_mut() {
865            group
866                .members
867                .values_mut()
868                .for_each(|confirmed| *confirmed = false);
869        }
870        self.provisional_until = None;
871        self.initiated_at = None;
872        self.state = EcnState::Initiating;
873        self.since_probe = PROBE_SPACING;
874        self.last_probe = None;
875        self.probes_confirmed = 0;
876        self.probes_lost = 0;
877        self.window = Window::default();
878    }
879
880    /// RFC 6679 sections 7.2.1 and 7.4.2: a detected failure is logged ("they should log these
881    /// to enable follow up") and kept for the application.
882    fn record(&mut self, failure: EcnFailure) {
883        if failure.is_initiation_failure() {
884            log::warn!("ECN: {failure}; packets go out Not-ECT");
885        } else {
886            log::warn!("ECN: {failure}");
887        }
888        if self.failures.len() == MAX_KEPT_FAILURES {
889            self.failures.remove(0);
890        }
891        self.failures.push(failure);
892    }
893
894    /// The failures detected since the last call, oldest first (at most sixteen are kept).
895    pub fn take_failures(&mut self) -> Vec<EcnFailure> {
896        std::mem::take(&mut self.failures)
897    }
898
899    fn fail(&mut self, now: Instant, failure: EcnFailure) {
900        self.record(failure);
901        self.state = EcnState::Failed {
902            retry_at: now + self.retry_after,
903        };
904        self.window = Window::default();
905    }
906}
907
908#[cfg(test)]
909mod tests {
910    use super::*;
911
912    /// RFC 6679 counters for `marked` probes and the unmarked rest of `first..=last`, as a
913    /// receiver on a path that `ect_arrives` (or clears the field) counts them.
914    fn counters_for(
915        sent: &[u16],
916        marked: &[u16],
917        ect_arrives: bool,
918        lost: u16,
919        base: EcnCounters,
920    ) -> EcnCounters {
921        let marked_count = marked.len() as u32;
922        let unmarked = (sent.len() - marked.len()) as u16;
923        let mut c = base;
924        if ect_arrives {
925            c.ect1 += marked_count - u32::from(lost.min(marked_count as u16));
926            c.not_ect += unmarked;
927        } else {
928            c.not_ect += unmarked + marked_count as u16 - lost;
929        }
930        c.lost += lost;
931        c
932    }
933
934    /// RFC 6679 7.2.1 with the counters of section 5: probes counted ECT by the receiver's
935    /// ECN Feedback / XR ECN Summary Reports make the initiation succeed, and every packet is
936    /// then sent ECT (section 7.3.1).
937    /// RFC 6679 section 7.2: one initiation method per RTP session. Bundled sections that
938    /// negotiated different methods use the first one's; another transport keeps its own.
939    #[test]
940    fn bundled_sections_use_one_initiation_method() {
941        use EcnInitiation::{LeapOfFaith, RtpAndRtcp};
942        let methods = EcnInitiation::one_per_transport(&[
943            (0, Some(RtpAndRtcp)),
944            (0, Some(LeapOfFaith)),
945            (0, None),
946            (1, Some(LeapOfFaith)),
947        ]);
948        assert_eq!(
949            methods,
950            vec![Some(RtpAndRtcp), Some(RtpAndRtcp), None, Some(LeapOfFaith)]
951        );
952    }
953
954    #[test]
955    fn the_ect_parameter_names_ect0_ect1_or_random_and_nothing_else() {
956        assert_eq!(EctPreference::from_sdp("0"), Some(EctPreference::Ect0));
957        assert_eq!(EctPreference::from_sdp(" 1"), Some(EctPreference::Ect1));
958        assert_eq!(
959            EctPreference::from_sdp("Random"),
960            Some(EctPreference::Random)
961        );
962        assert_eq!(EctPreference::from_sdp("2"), None);
963        assert_eq!(
964            EcnMarking::Rfc6679.codepoint(None, true),
965            shared::EcnCodepoint::Ect0,
966            "RFC 6679 section 7.3.1: ECT(0) unless asked"
967        );
968        assert_eq!(
969            EcnMarking::L4s.codepoint(Some(EctPreference::Ect0), false),
970            shared::EcnCodepoint::Ect1
971        );
972    }
973
974    #[test]
975    fn counted_ect_probes_complete_the_initiation() {
976        let mut v = EcnValidation::default();
977        let mut at = Instant::now();
978        let sent: Vec<u16> = (0..40).collect();
979        let marked = send(&mut v, &mut at, 0, 40);
980        assert!(
981            marked.len() >= 2 && marked.len() < 40,
982            "probes only: {marked:?}"
983        );
984        let c = counters_for(&sent, &marked, true, 0, EcnCounters::default());
985        v.on_counters(at, 39, c);
986        assert_eq!(v.state(), EcnState::Active);
987        assert_eq!(
988            send(&mut v, &mut at, 40, 10).len(),
989            10,
990            "all marked once active"
991        );
992    }
993
994    /// Section 7.2.1: a path that clears the field (probes counted not-ECT) fails the
995    /// initiation; section 7.4.1: it is retried later.
996    #[test]
997    fn probes_counted_not_ect_fail_the_initiation() {
998        let mut v = EcnValidation::default().with_retry_after(Duration::from_secs(10));
999        let mut at = Instant::now();
1000        let sent: Vec<u16> = (0..40).collect();
1001        let marked = send(&mut v, &mut at, 0, 40);
1002        let c = counters_for(&sent, &marked, false, 0, EcnCounters::default());
1003        v.on_counters(at, 39, c);
1004        assert!(
1005            matches!(v.state(), EcnState::Failed { .. }),
1006            "{:?}",
1007            v.state()
1008        );
1009        assert!(
1010            send(&mut v, &mut at, 40, 20).is_empty(),
1011            "nothing marked after the failure"
1012        );
1013        at += Duration::from_secs(11);
1014        assert!(
1015            !send(&mut v, &mut at, 60, 20).is_empty(),
1016            "probing again after the retry time"
1017        );
1018    }
1019
1020    /// Section 7.4.2, ongoing use: once every packet goes out ECT, a receiver counting them
1021    /// not-ECT means the path clears the field, and marking stops.
1022    #[test]
1023    fn bleaching_counted_in_ongoing_use_stops_the_marking() {
1024        let mut v = EcnValidation::new(EcnInitiation::LeapOfFaith);
1025        let mut at = Instant::now();
1026        let sent: Vec<u16> = (0..40).collect();
1027        let marked = send(&mut v, &mut at, 0, 40);
1028        assert_eq!(marked.len(), 40);
1029        let c = counters_for(&sent, &marked, false, 0, EcnCounters::default());
1030        v.on_counters(at, 39, c);
1031        assert!(
1032            matches!(v.state(), EcnState::Failed { .. }),
1033            "{:?}",
1034            v.state()
1035        );
1036    }
1037
1038    /// Section 7.4.1: high loss of ECT packets switches to not-ECT to compare.
1039    #[test]
1040    fn counted_loss_of_ect_packets_falls_back_to_not_ect() {
1041        let mut v = EcnValidation::new(EcnInitiation::LeapOfFaith);
1042        let mut at = Instant::now();
1043        let sent: Vec<u16> = (0..40).collect();
1044        let marked = send(&mut v, &mut at, 0, 40);
1045        let c = counters_for(&sent, &marked, true, 20, EcnCounters::default());
1046        v.on_counters(at, 39, c);
1047        assert_eq!(v.state(), EcnState::Fallback);
1048        assert!(send(&mut v, &mut at, 40, 10).is_empty());
1049    }
1050
1051    /// Sends `count` packets 20 ms apart from `first`; returns which were marked.
1052    fn send(v: &mut EcnValidation, at: &mut Instant, first: u16, count: u16) -> Vec<u16> {
1053        let mut marked = vec![];
1054        for n in 0..count {
1055            let seq = first.wrapping_add(n);
1056            if v.on_send(*at, seq) {
1057                marked.push(seq);
1058            }
1059            *at += Duration::from_millis(20);
1060        }
1061        marked
1062    }
1063
1064    /// [`report`] from the participant `reporter`.
1065    fn report_from(
1066        v: &mut EcnValidation,
1067        at: Instant,
1068        reporter: Option<&str>,
1069        first: u16,
1070        count: u16,
1071        path: impl Fn(u16, bool) -> Option<Ecn>,
1072    ) {
1073        for n in 0..count {
1074            let seq = first.wrapping_add(n);
1075            let marked = v.was_marked(seq);
1076            match path(seq, marked) {
1077                Some(ecn) => v.on_report_from(at, reporter, seq, true, ecn),
1078                None => v.on_report_from(at, reporter, seq, false, Ecn::NotEct),
1079            }
1080        }
1081    }
1082
1083    /// Reports `first..first + count`: `path(seq, marked)` says how each arrived.
1084    fn report(
1085        v: &mut EcnValidation,
1086        at: Instant,
1087        first: u16,
1088        count: u16,
1089        path: impl Fn(u16, bool) -> Option<Ecn>,
1090    ) {
1091        for n in 0..count {
1092            let seq = first.wrapping_add(n);
1093            let marked = v.was_marked(seq);
1094            match path(seq, marked) {
1095                Some(ecn) => v.on_report(at, seq, true, ecn),
1096                None => v.on_report(at, seq, false, Ecn::NotEct),
1097            }
1098        }
1099    }
1100
1101    fn carries_ecn(_: u16, marked: bool) -> Option<Ecn> {
1102        Some(if marked { Ecn::Ect1 } else { Ecn::NotEct })
1103    }
1104
1105    /// RFC 6679 section 7.2.1: after a provisional success, another RTCP CNAME within three
1106    /// reporting intervals of the initiation's start sends the sender back to probing; the
1107    /// same CNAME again does not.
1108    #[test]
1109    fn a_second_cname_during_a_provisional_success_sends_the_stream_back_to_probing() {
1110        let mut v = EcnValidation::default();
1111        let mut at = Instant::now();
1112        v.on_remote_cname(at, "peer");
1113        send(&mut v, &mut at, 0, 40);
1114        report(&mut v, at, 0, 40, carries_ecn);
1115        assert!(v.is_provisional(at));
1116        v.on_remote_cname(at, "peer");
1117        assert_eq!(v.state(), EcnState::Active, "the same receiver");
1118        assert!(!v.is_group());
1119        v.on_remote_cname(at, "another participant");
1120        assert_eq!(v.state(), EcnState::Initiating);
1121        assert!(v.is_group());
1122        let probes = send(&mut v, &mut at, 40, 40).len();
1123        assert!((1..40).contains(&probes), "a small fraction only: {probes}");
1124    }
1125
1126    /// RFC 6679 section 7.2.1, the full procedure a group of participants needs: "An RTP sender
1127    /// shall consider the group membership to be stable after it has been in the session and
1128    /// sending ECT-marked probe packets for at least three RTCP reporting intervals ... and when
1129    /// a complete RTCP reporting interval has passed without changes to the group membership.
1130    /// ECN initiation is considered successful when the group membership is stable and all
1131    /// known participants have sent [reports] indicating correct receipt". Confirmations from
1132    /// one participant are not enough, nor are all of them before the membership is stable,
1133    /// and a participant that joins needs its own confirmation and another stable interval.
1134    #[test]
1135    fn a_group_initiation_succeeds_only_when_every_participant_confirmed_a_stable_membership() {
1136        let mut v = EcnValidation::default();
1137        let start = Instant::now();
1138        let mut at = start;
1139        v.on_remote_cname(at, "alice");
1140        v.on_remote_cname(at, "bob");
1141        assert!(v.is_group(), "two CNAMEs before the first probe");
1142        let mut seq = 0u16;
1143        // 50 packets (one second), reported by `who`.
1144        fn round(v: &mut EcnValidation, at: &mut Instant, seq: &mut u16, who: &[&str]) {
1145            send(v, at, *seq, 50);
1146            for reporter in who {
1147                report_from(v, *at, Some(reporter), *seq, 50, carries_ecn);
1148            }
1149            *seq = seq.wrapping_add(50);
1150        }
1151
1152        // Alice confirms, over and over, past three intervals: not enough.
1153        while at < start + PROVISIONAL_MONITOR + REPORTING_INTERVAL {
1154            round(&mut v, &mut at, &mut seq, &["alice"]);
1155        }
1156        assert_eq!(v.state(), EcnState::Initiating, "bob has not confirmed");
1157        // Unattributed reports count for no one.
1158        let first = seq;
1159        send(&mut v, &mut at, first, 10);
1160        report(&mut v, at, first, 10, carries_ecn);
1161        seq = first + 10;
1162        assert_eq!(v.state(), EcnState::Initiating);
1163
1164        // A third participant joins; then Bob and Alice confirm.
1165        v.on_remote_cname(at, "carol");
1166        let joined = at;
1167        round(&mut v, &mut at, &mut seq, &["alice", "bob"]);
1168        assert_eq!(v.state(), EcnState::Initiating, "carol has not confirmed");
1169        // Carol confirms at once; the membership changed less than an interval ago.
1170        round(&mut v, &mut at, &mut seq, &["carol"]);
1171        assert!(at < joined + REPORTING_INTERVAL);
1172        assert_eq!(v.state(), EcnState::Initiating, "not stable yet");
1173        // A complete interval without a change: every packet is marked.
1174        while at < joined + REPORTING_INTERVAL {
1175            round(&mut v, &mut at, &mut seq, &[]);
1176        }
1177        let marked = send(&mut v, &mut at, seq, 10);
1178        assert_eq!(v.state(), EcnState::Active);
1179        assert_eq!(marked.len(), 10, "all marked once the group confirmed");
1180        assert!(
1181            !v.is_provisional(at),
1182            "a full success, not a provisional one"
1183        );
1184    }
1185
1186    #[test]
1187    fn initiation_marks_a_small_fraction_never_all() {
1188        let mut v = EcnValidation::default();
1189        let mut at = Instant::now();
1190        let marked = send(&mut v, &mut at, 0, 100);
1191        assert!(marked.len() >= 4, "probes: {marked:?}");
1192        assert!(marked.len() <= 100 / 4, "a small fraction: {marked:?}");
1193        assert!(
1194            marked.windows(2).all(|w| w[1] - w[0] >= 2),
1195            "never two in a row: {marked:?}"
1196        );
1197        assert_eq!(v.state(), EcnState::Initiating);
1198    }
1199
1200    #[test]
1201    fn a_slow_stream_still_probes_twice_a_second() {
1202        let mut v = EcnValidation::default();
1203        let mut at = Instant::now();
1204        let mut marked = 0;
1205        // Five packets a second for two seconds.
1206        for seq in 0..10u16 {
1207            marked += u32::from(v.on_send(at, seq));
1208            at += Duration::from_millis(200);
1209        }
1210        assert!(marked >= 4, "{marked} probes in two seconds");
1211        assert!(marked < 10);
1212    }
1213
1214    #[test]
1215    fn confirmed_probes_make_every_packet_ect() {
1216        let mut v = EcnValidation::default();
1217        let mut at = Instant::now();
1218        send(&mut v, &mut at, 0, 40);
1219        report(&mut v, at, 0, 40, carries_ecn);
1220        assert_eq!(v.state(), EcnState::Active);
1221        assert_eq!(send(&mut v, &mut at, 40, 20).len(), 20);
1222        assert!(v.marks_all());
1223    }
1224
1225    #[test]
1226    fn a_ce_marked_probe_confirms_ecn_too() {
1227        let mut v = EcnValidation::default();
1228        let mut at = Instant::now();
1229        send(&mut v, &mut at, 0, 40);
1230        report(&mut v, at, 0, 40, |_, m| {
1231            Some(if m { Ecn::Ce } else { Ecn::NotEct })
1232        });
1233        assert_eq!(v.state(), EcnState::Active);
1234    }
1235
1236    #[test]
1237    fn a_bleached_probe_fails_the_initiation_and_a_retry_follows() {
1238        let mut v = EcnValidation::default().with_retry_after(Duration::from_secs(10));
1239        let mut at = Instant::now();
1240        send(&mut v, &mut at, 0, 40);
1241        report(&mut v, at, 0, 40, |_, _| Some(Ecn::NotEct));
1242        assert!(
1243            matches!(v.state(), EcnState::Failed { .. }),
1244            "{:?}",
1245            v.state()
1246        );
1247        assert!(send(&mut v, &mut at, 40, 100).is_empty(), "nothing marked");
1248        at += Duration::from_secs(10);
1249        assert!(
1250            !send(&mut v, &mut at, 140, 20).is_empty(),
1251            "initiating again"
1252        );
1253        assert_eq!(v.state(), EcnState::Initiating);
1254    }
1255
1256    #[test]
1257    fn a_path_that_drops_ect_packets_fails_the_initiation() {
1258        let mut v = EcnValidation::default();
1259        let mut at = Instant::now();
1260        let probes = send(&mut v, &mut at, 0, 60);
1261        assert!(probes.len() >= 4);
1262        report(&mut v, at, 0, 60, |_, m| (!m).then_some(Ecn::NotEct));
1263        assert!(
1264            matches!(v.state(), EcnState::Failed { .. }),
1265            "{:?}",
1266            v.state()
1267        );
1268    }
1269
1270    #[test]
1271    fn three_lost_probes_are_not_yet_a_failure() {
1272        let mut v = EcnValidation::default();
1273        let mut at = Instant::now();
1274        let probes = send(&mut v, &mut at, 0, 60);
1275        let lost: Vec<u16> = probes[..3].to_vec();
1276        report(&mut v, at, 0, 60, |s, m| {
1277            if lost.contains(&s) {
1278                None
1279            } else {
1280                carries_ecn(s, m)
1281            }
1282        });
1283        assert_eq!(v.state(), EcnState::Active, "the fourth probe arrived ECT");
1284    }
1285
1286    #[test]
1287    fn a_late_packet_reported_lost_then_received_is_not_a_loss() {
1288        let mut v = EcnValidation::default();
1289        let mut at = Instant::now();
1290        let probes = send(&mut v, &mut at, 0, 60);
1291        for &p in &probes {
1292            v.on_report(at, p, false, Ecn::NotEct);
1293            v.on_report(at, p, true, Ecn::Ect1);
1294            // A repeat of either report changes nothing.
1295            v.on_report(at, p, true, Ecn::Ect1);
1296            v.on_report(at, p, false, Ecn::NotEct);
1297        }
1298        assert_eq!(v.state(), EcnState::Active);
1299    }
1300
1301    #[test]
1302    fn bleaching_during_use_stops_the_marking() {
1303        let mut v = EcnValidation::new(EcnInitiation::LeapOfFaith);
1304        let mut at = Instant::now();
1305        assert_eq!(
1306            send(&mut v, &mut at, 0, 32).len(),
1307            32,
1308            "leap of faith marks all"
1309        );
1310        // A few bleached packets are not a failure.
1311        report(&mut v, at, 0, 32, |s, _| {
1312            Some(if s % 16 == 0 { Ecn::NotEct } else { Ecn::Ect1 })
1313        });
1314        assert_eq!(v.state(), EcnState::Active);
1315        send(&mut v, &mut at, 32, 32);
1316        report(&mut v, at, 32, 32, |_, _| Some(Ecn::NotEct));
1317        assert!(
1318            matches!(v.state(), EcnState::Failed { .. }),
1319            "{:?}",
1320            v.state()
1321        );
1322        assert!(send(&mut v, &mut at, 64, 50).is_empty());
1323    }
1324
1325    /// RFC 6679 section 7.2.3: under the leap of faith, a receiver report showing no reception
1326    /// is not enough (the receiver may have reported before any packet reached it); the second
1327    /// in a row ends the marking. A report showing reception in between starts the count over,
1328    /// and once reception was shown the path is taken as carrying ECT.
1329    #[test]
1330    fn leap_of_faith_waits_for_a_second_report_without_reception() {
1331        let mut v = EcnValidation::new(EcnInitiation::LeapOfFaith);
1332        let mut at = Instant::now();
1333        // Nothing sent yet: a report says nothing.
1334        v.on_report_without_reception(at);
1335        v.on_report_without_reception(at);
1336        assert_eq!(v.state(), EcnState::Active);
1337        assert_eq!(send(&mut v, &mut at, 0, 10).len(), 10);
1338        v.on_report_without_reception(at);
1339        assert_eq!(v.state(), EcnState::Active, "one report is not enough");
1340        v.on_report_without_reception(at);
1341        assert!(
1342            matches!(v.state(), EcnState::Failed { .. }),
1343            "{:?}",
1344            v.state()
1345        );
1346        assert_eq!(v.take_failures(), vec![EcnFailure::NoReception]);
1347        assert!(
1348            send(&mut v, &mut at, 10, 10).is_empty(),
1349            "Not-ECT after the failure"
1350        );
1351
1352        let mut v = EcnValidation::new(EcnInitiation::LeapOfFaith);
1353        send(&mut v, &mut at, 0, 10);
1354        v.on_report_without_reception(at);
1355        v.on_reception_reported();
1356        v.on_report_without_reception(at);
1357        v.on_report_without_reception(at);
1358        assert_eq!(v.state(), EcnState::Active, "reception was reported");
1359
1360        // The probing initiation does not use the rule.
1361        let mut v = EcnValidation::new(EcnInitiation::RtpAndRtcp);
1362        send(&mut v, &mut at, 0, 40);
1363        v.on_report_without_reception(at);
1364        v.on_report_without_reception(at);
1365        assert!(v.take_failures().is_empty());
1366    }
1367
1368    #[test]
1369    fn loss_that_goes_with_the_marking_initiates_again_then_disables() {
1370        let mut v = EcnValidation::new(EcnInitiation::LeapOfFaith);
1371        let mut at = Instant::now();
1372        let mut seq = 0u16;
1373        for round in 0..FALLBACKS_TO_DISABLE {
1374            // In use: ECT packets are dropped.
1375            if round > 0 {
1376                // Initiate again: probes go through, so the stream is back in use.
1377                let n = 40;
1378                send(&mut v, &mut at, seq, n);
1379                report(&mut v, at, seq, n, carries_ecn);
1380                seq += n;
1381            }
1382            assert_eq!(v.state(), EcnState::Active, "round {round}");
1383            send(&mut v, &mut at, seq, 32);
1384            report(&mut v, at, seq, 32, |_, m| (!m).then_some(Ecn::NotEct));
1385            seq += 32;
1386            assert_eq!(v.state(), EcnState::Fallback, "round {round}");
1387            assert!(
1388                send(&mut v, &mut at, seq, 32).is_empty(),
1389                "Not-ECT while comparing"
1390            );
1391            report(&mut v, at, seq, 32, |_, m| (!m).then_some(Ecn::NotEct));
1392            seq += 32;
1393        }
1394        assert_eq!(v.state(), EcnState::Disabled);
1395        at += DEFAULT_RETRY_AFTER * 2;
1396        assert!(
1397            send(&mut v, &mut at, seq, 40).is_empty(),
1398            "disabled for good"
1399        );
1400        // RFC 6679 section 7.4.2: the erroneous behaviour detected is kept for follow-up, each
1401        // fallback and the final one.
1402        let mut expected =
1403            vec![EcnFailure::EctLost { disabled: false }; FALLBACKS_TO_DISABLE as usize - 1];
1404        expected.push(EcnFailure::EctLost { disabled: true });
1405        assert_eq!(v.take_failures(), expected);
1406        assert!(v.take_failures().is_empty(), "taken once");
1407    }
1408
1409    #[test]
1410    fn loss_that_stays_without_the_marking_resumes_it() {
1411        let mut v = EcnValidation::new(EcnInitiation::LeapOfFaith);
1412        let mut at = Instant::now();
1413        send(&mut v, &mut at, 0, 32);
1414        report(&mut v, at, 0, 32, |s, _| (s % 2 == 0).then_some(Ecn::Ect1));
1415        assert_eq!(v.state(), EcnState::Fallback);
1416        send(&mut v, &mut at, 32, 32);
1417        report(&mut v, at, 32, 32, |s, _| {
1418            (s % 2 == 0).then_some(Ecn::NotEct)
1419        });
1420        assert_eq!(v.state(), EcnState::Active, "congestion, not ECN");
1421    }
1422
1423    /// A fixed corpus of arbitrary send / report sequences (sequence numbers that jump, wrap,
1424    /// repeat; reports out of order, duplicated, for unknown packets): nothing panics, a stream
1425    /// that is initiating never marks two packets in a row nor more than a quarter of them,
1426    /// and one that is disabled never marks again.
1427    #[test]
1428    fn arbitrary_send_and_report_sequences_keep_the_invariants() {
1429        let mut state = 0x0EC0_0001u32;
1430        let mut next = move || {
1431            state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
1432            state >> 8
1433        };
1434        for _ in 0..400 {
1435            let mut v = if next() % 2 == 0 {
1436                EcnValidation::default()
1437            } else {
1438                EcnValidation::new(EcnInitiation::LeapOfFaith)
1439            }
1440            .with_retry_after(Duration::from_millis(u64::from(next() % 3000)));
1441            let mut at = Instant::now();
1442            let mut seq = next() as u16;
1443            let mut sent: Vec<u16> = vec![];
1444            let mut run_marked = 0u32;
1445            let mut initiating = (0u32, 0u32);
1446            for _ in 0..600 {
1447                at += Duration::from_millis(u64::from(next() % 60));
1448                match next() % 10 {
1449                    0..=5 => {
1450                        seq = match next() % 20 {
1451                            0 => seq.wrapping_add(next() as u16),
1452                            1 => seq,
1453                            _ => seq.wrapping_add(1),
1454                        };
1455                        let was = v.state();
1456                        let marked = v.on_send(at, seq);
1457                        sent.push(seq);
1458                        if was == EcnState::Disabled {
1459                            assert!(!marked, "a disabled stream marks nothing");
1460                        }
1461                        if v.state() == EcnState::Initiating && was == EcnState::Initiating {
1462                            initiating.0 += 1;
1463                            initiating.1 += u32::from(marked);
1464                            run_marked = if marked { run_marked + 1 } else { 0 };
1465                            assert!(run_marked <= 1, "two probes in a row");
1466                        } else {
1467                            run_marked = 0;
1468                        }
1469                    }
1470                    _ => {
1471                        let target = if sent.is_empty() || next() % 8 == 0 {
1472                            next() as u16
1473                        } else {
1474                            sent[(next() as usize) % sent.len()]
1475                        };
1476                        let ecn = match next() % 4 {
1477                            0 => Ecn::NotEct,
1478                            1 => Ecn::Ect1,
1479                            2 => Ecn::Ect0,
1480                            _ => Ecn::Ce,
1481                        };
1482                        v.on_report(at, target, next() % 5 != 0, ecn);
1483                    }
1484                }
1485            }
1486            if initiating.0 >= 40 {
1487                assert!(
1488                    initiating.1 * 4 <= initiating.0 + 4,
1489                    "a small fraction while initiating: {initiating:?}"
1490                );
1491            }
1492        }
1493    }
1494}