Skip to main content

rtci_interceptor/rtpfb/
convert.rs

1//! Turning the two feedback formats into a common [`Acknowledgement`].
2//!
3//! TWCC and RFC 8888 answer the same question — which packets arrived, and when — in different
4//! shapes. Converting both to one type is what lets congestion control read either without
5//! knowing which is negotiated.
6
7use super::acknowledgement::Acknowledgement;
8use rtcp::transport_feedbacks::cc_feedback_report::{CcFeedbackReport, Ecn};
9use rtcp::transport_feedbacks::transport_layer_cc::{
10    PacketStatusChunk, ReferenceTimeUnwrapper, SymbolTypeTcc, TransportLayerCc,
11};
12use std::collections::HashMap;
13use std::time::Duration;
14
15/// TWCC's reference time counts in multiples of 64 ms.
16const TWCC_REFERENCE_TICK: Duration = Duration::from_millis(64);
17
18/// TWCC receive deltas are in microseconds.
19const TWCC_DELTA_UNIT: Duration = Duration::from_micros(1);
20
21/// RFC 8888 arrival offsets are in units of 1/1024 s.
22const CCFB_OFFSET_DENOMINATOR: u32 = 1024;
23
24/// The RFC 8888 offset meaning "arrived after the report timestamp", which carries no usable
25/// arrival time.
26const CCFB_OFFSET_AFTER_REPORT: u16 = 0x1FFF;
27
28/// The RFC 8888 offset meaning "arrived 8189/1024 s or more before the report timestamp": the
29/// packet arrived, but when is not known (RFC 8888 section 3.1).
30const CCFB_OFFSET_TOO_OLD: u16 = 0x1FFE;
31
32/// RFC 8888 report timestamps are the middle 32 bits of an NTP timestamp: units of 1/65536 s.
33const CCFB_TIMESTAMP_DENOMINATOR: f64 = 65_536.0;
34
35/// A counter of `bits` bits that wraps, followed from one reading to the next.
36#[derive(Debug, Clone, Copy)]
37struct WrappingCounter {
38    bits: u32,
39    /// The last raw reading and the extended value it was given.
40    last: Option<(u32, u64)>,
41}
42
43impl WrappingCounter {
44    const fn new(bits: u32) -> Self {
45        Self { bits, last: None }
46    }
47
48    /// The reading as a count that does not wrap. The first reading is placed one full period
49    /// up, so a later reading a little *behind* it (feedback read out of order) does not go
50    /// below zero.
51    fn extend(&mut self, raw: u32) -> u64 {
52        let period = 1u64 << self.bits;
53        let raw = u64::from(raw) & (period - 1);
54        let extended = match self.last {
55            None => period + raw,
56            Some((last_raw, last_extended)) => {
57                // The shorter way round the circle: forwards if less than half a period ahead,
58                // backwards otherwise.
59                let ahead = raw.wrapping_sub(u64::from(last_raw)) & (period - 1);
60                if ahead < period / 2 {
61                    last_extended + ahead
62                } else {
63                    last_extended.saturating_sub(period - ahead)
64                }
65            }
66        };
67        self.last = Some((raw as u32, extended));
68        extended
69    }
70}
71
72/// The receiver's clock as successive feedback reports give it, without the wraps.
73///
74/// Both feedback formats time arrivals against a short counter: TWCC's reference time is 24 bits
75/// of 64 ms (it wraps every 12.4 days, and is a signed value, so a receiver may start it
76/// anywhere), RFC 8888's report timestamp is 32 bits of 1/65536 s (it wraps every 18.2 hours).
77/// Arrival times are only useful as differences, across reports as much as within one, so the
78/// counters have to be followed through their wraps: read raw, the report after a wrap places
79/// its arrivals days before the previous report's.
80///
81/// One per connection, fed every report in the order it is read.
82#[derive(Debug, Clone)]
83pub struct FeedbackTimeline {
84    twcc_reference: ReferenceTimeUnwrapper,
85    ccfb_timestamp: WrappingCounter,
86}
87
88impl Default for FeedbackTimeline {
89    fn default() -> Self {
90        Self {
91            twcc_reference: ReferenceTimeUnwrapper::new(),
92            ccfb_timestamp: WrappingCounter::new(32),
93        }
94    }
95}
96
97impl FeedbackTimeline {
98    /// A timeline that has seen no report yet.
99    pub fn new() -> Self {
100        Self::default()
101    }
102
103    /// Convert a TWCC feedback packet, placing its arrivals after those of the reports before
104    /// it.
105    pub fn convert_twcc(&mut self, feedback: &TransportLayerCc) -> Vec<Acknowledgement> {
106        // Signed ticks from the receiver's own origin; one period is added so a reference time
107        // that starts negative, or steps back a little, stays a non-negative duration.
108        let ticks = self.twcc_reference.unwrap(feedback.reference_time) + (1i64 << 24);
109        twcc_acknowledgements(
110            feedback,
111            Duration::from_millis(ticks.max(0) as u64 * TWCC_REFERENCE_TICK.as_millis() as u64),
112        )
113    }
114
115    /// Convert an RFC 8888 report, placing its arrivals after those of the reports before it.
116    pub fn convert_ccfb(
117        &mut self,
118        feedback: &CcFeedbackReport,
119    ) -> (Duration, HashMap<u32, Vec<Acknowledgement>>) {
120        let units = self.ccfb_timestamp.extend(feedback.report_timestamp);
121        ccfb_acknowledgements(
122            feedback,
123            Duration::from_secs_f64(units as f64 / CCFB_TIMESTAMP_DENOMINATOR),
124        )
125    }
126}
127
128/// Convert a TWCC feedback packet into one acknowledgement per reported packet.
129///
130/// Arrival times are relative to the feedback's own 24-bit reference time, so they are comparable
131/// across successive TWCC reports only until that counter wraps: a connection converts through a
132/// [`FeedbackTimeline`], which follows it.
133pub fn convert_twcc(feedback: &TransportLayerCc) -> Vec<Acknowledgement> {
134    twcc_acknowledgements(feedback, TWCC_REFERENCE_TICK * feedback.reference_time)
135}
136
137/// The acknowledgements of one TWCC feedback packet whose reference time is `reference` on the
138/// receiver's clock.
139fn twcc_acknowledgements(feedback: &TransportLayerCc, reference: Duration) -> Vec<Acknowledgement> {
140    let mut acknowledgements = Vec::new();
141
142    // The reference time is a count of 64 ms ticks on the receiver's clock; deltas accumulate
143    // from there, so each arrival depends on every arrival before it in the same report.
144    let mut arrival = reference;
145    let mut delta_index = 0usize;
146    let mut offset = 0u16;
147
148    let push = |symbol: SymbolTypeTcc,
149                offset: &mut u16,
150                arrival: &mut Duration,
151                delta_index: &mut usize,
152                acknowledgements: &mut Vec<Acknowledgement>| {
153        let sequence_number = feedback.base_sequence_number.wrapping_add(*offset);
154        *offset = offset.wrapping_add(1);
155
156        match symbol {
157            SymbolTypeTcc::PacketNotReceived => {
158                acknowledgements.push(Acknowledgement::lost(sequence_number));
159            }
160            SymbolTypeTcc::PacketReceivedSmallDelta | SymbolTypeTcc::PacketReceivedLargeDelta => {
161                // A delta may be negative — packets can be reported out of order — so the running
162                // arrival is adjusted in whichever direction the report says.
163                if let Some(delta) = feedback.recv_deltas.get(*delta_index) {
164                    *delta_index += 1;
165                    let magnitude = TWCC_DELTA_UNIT * delta.delta.unsigned_abs() as u32;
166                    *arrival = if delta.delta < 0 {
167                        arrival.saturating_sub(magnitude)
168                    } else {
169                        *arrival + magnitude
170                    };
171                    acknowledgements.push(Acknowledgement::received(
172                        sequence_number,
173                        Some(*arrival),
174                        Ecn::NotEct,
175                    ));
176                } else {
177                    // The chunks claim more received packets than there are deltas. Report the
178                    // packet as arrived without a time rather than inventing one.
179                    acknowledgements.push(Acknowledgement::received(
180                        sequence_number,
181                        None,
182                        Ecn::NotEct,
183                    ));
184                }
185            }
186            SymbolTypeTcc::PacketReceivedWithoutDelta => {
187                acknowledgements.push(Acknowledgement::received(
188                    sequence_number,
189                    None,
190                    Ecn::NotEct,
191                ));
192            }
193        }
194    };
195
196    // The header's packet status count is the number of packets the report describes. A
197    // run-length chunk can claim a run of up to 8191 whatever the count says, so the chunks are
198    // walked only as far as the count: one small feedback packet must not expand into millions
199    // of acknowledgements.
200    let symbols = feedback
201        .packet_chunks
202        .iter()
203        .flat_map(|chunk| -> Box<dyn Iterator<Item = SymbolTypeTcc> + '_> {
204            match chunk {
205                PacketStatusChunk::RunLengthChunk(run) => Box::new(std::iter::repeat_n(
206                    run.packet_status_symbol,
207                    run.run_length as usize,
208                )),
209                PacketStatusChunk::StatusVectorChunk(vector) => {
210                    Box::new(vector.symbol_list.iter().copied())
211                }
212            }
213        })
214        .take(feedback.packet_status_count as usize);
215
216    for symbol in symbols {
217        push(
218            symbol,
219            &mut offset,
220            &mut arrival,
221            &mut delta_index,
222            &mut acknowledgements,
223        );
224    }
225
226    acknowledgements
227}
228
229/// Convert an RFC 8888 report into acknowledgements per media stream, with the delay the receiver
230/// added before sending it.
231///
232/// The returned delay is the gap between the newest arrival the report describes and the instant
233/// it was stamped. A round trip measured without subtracting it counts the receiver's own
234/// reporting interval as network time.
235///
236/// Each arrival time is the report timestamp minus the packet's arrival time offset (RFC 8888
237/// section 3.1), on the receiver's clock: a later arrival is a larger value, within a report and
238/// from one report to the next, until the 32-bit report timestamp wraps. A connection converts
239/// through a [`FeedbackTimeline`], which follows the wrap.
240pub fn convert_ccfb(feedback: &CcFeedbackReport) -> (Duration, HashMap<u32, Vec<Acknowledgement>>) {
241    FeedbackTimeline::new().convert_ccfb(feedback)
242}
243
244/// The acknowledgements of one RFC 8888 report stamped at `report_time` on the receiver's clock.
245fn ccfb_acknowledgements(
246    feedback: &CcFeedbackReport,
247    report_time: Duration,
248) -> (Duration, HashMap<u32, Vec<Acknowledgement>>) {
249    let mut per_stream = HashMap::new();
250    // Arrivals are offsets *back* from the report timestamp, so the newest arrival is the
251    // smallest offset.
252    let mut newest_arrival: Option<Duration> = None;
253
254    for block in &feedback.report_blocks {
255        let mut acknowledgements = Vec::with_capacity(block.metric_blocks.len());
256
257        for (index, metric) in block.metric_blocks.iter().enumerate() {
258            let sequence_number = block.begin_sequence.wrapping_add(index as u16);
259
260            if !metric.received {
261                acknowledgements.push(Acknowledgement::lost(sequence_number));
262                continue;
263            }
264
265            // The two reserved offsets say the packet arrived after the report was stamped, or
266            // longer before it than the field can express. Neither is a measurement: the packet
267            // counts as received and contributes no arrival time.
268            let arrival = if metric.arrival_time_offset == CCFB_OFFSET_AFTER_REPORT
269                || metric.arrival_time_offset == CCFB_OFFSET_TOO_OLD
270            {
271                None
272            } else {
273                let offset = Duration::from_secs_f64(
274                    f64::from(metric.arrival_time_offset) / f64::from(CCFB_OFFSET_DENOMINATOR),
275                );
276                newest_arrival = Some(match newest_arrival {
277                    Some(newest) => newest.min(offset),
278                    None => offset,
279                });
280                // The offset counts *back* from the report timestamp.
281                Some(report_time.saturating_sub(offset))
282            };
283
284            acknowledgements.push(Acknowledgement::received(
285                sequence_number,
286                arrival,
287                metric.ecn,
288            ));
289        }
290
291        per_stream.insert(block.media_ssrc, acknowledgements);
292    }
293
294    (newest_arrival.unwrap_or_default(), per_stream)
295}
296
297#[cfg(test)]
298mod tests {
299    use super::*;
300    use rtcp::transport_feedbacks::cc_feedback_report::{
301        CcFeedbackMetricBlock, CcFeedbackReportBlock,
302    };
303    use rtcp::transport_feedbacks::transport_layer_cc::{
304        RecvDelta, RunLengthChunk, StatusVectorChunk,
305    };
306
307    fn run_length(symbol: SymbolTypeTcc, run_length: u16) -> PacketStatusChunk {
308        PacketStatusChunk::RunLengthChunk(RunLengthChunk {
309            packet_status_symbol: symbol,
310            run_length,
311            ..Default::default()
312        })
313    }
314
315    fn status_vector(symbols: Vec<SymbolTypeTcc>) -> PacketStatusChunk {
316        PacketStatusChunk::StatusVectorChunk(StatusVectorChunk {
317            symbol_list: symbols,
318            ..Default::default()
319        })
320    }
321
322    fn delta(microseconds: i64) -> RecvDelta {
323        RecvDelta {
324            delta: microseconds,
325            ..Default::default()
326        }
327    }
328
329    // ---------------------------------------------------------------------------------------
330    // TWCC
331    // ---------------------------------------------------------------------------------------
332
333    #[test]
334    fn a_run_of_lost_packets_converts_to_losses() {
335        let feedback = TransportLayerCc {
336            base_sequence_number: 100,
337            reference_time: 0,
338            packet_status_count: 3,
339            packet_chunks: vec![run_length(SymbolTypeTcc::PacketNotReceived, 3)],
340            recv_deltas: vec![],
341            ..Default::default()
342        };
343
344        let acknowledgements = convert_twcc(&feedback);
345        assert_eq!(
346            vec![
347                Acknowledgement::lost(100),
348                Acknowledgement::lost(101),
349                Acknowledgement::lost(102)
350            ],
351            acknowledgements
352        );
353    }
354
355    /// Deltas accumulate: each arrival is relative to the one before it, so a report describes a
356    /// *sequence* of arrivals rather than independent timestamps.
357    #[test]
358    fn deltas_accumulate_from_the_reference_time() {
359        let feedback = TransportLayerCc {
360            base_sequence_number: 10,
361            // One tick of 64 ms.
362            reference_time: 1,
363            packet_status_count: 3,
364            packet_chunks: vec![run_length(SymbolTypeTcc::PacketReceivedSmallDelta, 3)],
365            recv_deltas: vec![delta(1000), delta(2000), delta(500)],
366            ..Default::default()
367        };
368
369        let acknowledgements = convert_twcc(&feedback);
370        let arrivals: Vec<Duration> = acknowledgements
371            .iter()
372            .map(|ack| ack.arrival.expect("arrived with a time"))
373            .collect();
374
375        assert_eq!(
376            vec![
377                Duration::from_millis(64) + Duration::from_micros(1000),
378                Duration::from_millis(64) + Duration::from_micros(3000),
379                Duration::from_millis(64) + Duration::from_micros(3500),
380            ],
381            arrivals
382        );
383        assert!(acknowledgements.iter().all(|ack| ack.arrived));
384    }
385
386    /// Packets can be reported arriving out of order, which is a negative delta. Treating it as
387    /// positive would report the path as *less* delayed than it is.
388    #[test]
389    fn a_negative_delta_moves_the_arrival_backwards() {
390        let feedback = TransportLayerCc {
391            base_sequence_number: 0,
392            reference_time: 1,
393            packet_status_count: 2,
394            packet_chunks: vec![run_length(SymbolTypeTcc::PacketReceivedSmallDelta, 2)],
395            recv_deltas: vec![delta(5000), delta(-2000)],
396            ..Default::default()
397        };
398
399        let arrivals: Vec<Duration> = convert_twcc(&feedback)
400            .iter()
401            .map(|ack| ack.arrival.expect("arrived"))
402            .collect();
403
404        assert_eq!(
405            Duration::from_millis(64) + Duration::from_micros(5000),
406            arrivals[0]
407        );
408        assert_eq!(
409            Duration::from_millis(64) + Duration::from_micros(3000),
410            arrivals[1],
411            "the second packet arrived before the first"
412        );
413    }
414
415    #[test]
416    fn a_status_vector_converts_symbol_by_symbol() {
417        let feedback = TransportLayerCc {
418            base_sequence_number: 500,
419            reference_time: 0,
420            packet_status_count: 3,
421            packet_chunks: vec![status_vector(vec![
422                SymbolTypeTcc::PacketReceivedSmallDelta,
423                SymbolTypeTcc::PacketNotReceived,
424                SymbolTypeTcc::PacketReceivedLargeDelta,
425            ])],
426            recv_deltas: vec![delta(100), delta(200)],
427            ..Default::default()
428        };
429
430        let acknowledgements = convert_twcc(&feedback);
431        assert_eq!(
432            vec![true, false, true],
433            acknowledgements
434                .iter()
435                .map(|ack| ack.arrived)
436                .collect::<Vec<_>>()
437        );
438        assert_eq!(
439            vec![500, 501, 502],
440            acknowledgements
441                .iter()
442                .map(|ack| ack.sequence_number)
443                .collect::<Vec<_>>()
444        );
445    }
446
447    /// "Received without delta" means the receiver got it but cannot say when. Reporting an
448    /// invented time would feed congestion control a measurement nobody made.
449    #[test]
450    fn a_packet_received_without_a_delta_has_no_arrival_time() {
451        let feedback = TransportLayerCc {
452            base_sequence_number: 0,
453            reference_time: 0,
454            packet_status_count: 1,
455            packet_chunks: vec![run_length(SymbolTypeTcc::PacketReceivedWithoutDelta, 1)],
456            recv_deltas: vec![],
457            ..Default::default()
458        };
459
460        let acknowledgements = convert_twcc(&feedback);
461        assert!(acknowledgements[0].arrived);
462        assert_eq!(None, acknowledgements[0].arrival);
463    }
464
465    /// A report claiming more received packets than it carries deltas for is malformed. The
466    /// packets are still reported as arrived, without times, rather than panicking on the index.
467    #[test]
468    fn more_received_packets_than_deltas_does_not_panic() {
469        let feedback = TransportLayerCc {
470            base_sequence_number: 0,
471            reference_time: 0,
472            packet_status_count: 4,
473            packet_chunks: vec![run_length(SymbolTypeTcc::PacketReceivedSmallDelta, 4)],
474            recv_deltas: vec![delta(100)],
475            ..Default::default()
476        };
477
478        let acknowledgements = convert_twcc(&feedback);
479        assert_eq!(4, acknowledgements.len());
480        assert!(acknowledgements[0].arrival.is_some(), "the one real delta");
481        assert!(
482            acknowledgements[1..]
483                .iter()
484                .all(|ack| ack.arrival.is_none()),
485            "and no invented times for the rest"
486        );
487    }
488
489    #[test]
490    fn sequence_numbers_wrap_across_a_report() {
491        let feedback = TransportLayerCc {
492            base_sequence_number: 65534,
493            reference_time: 0,
494            packet_status_count: 4,
495            packet_chunks: vec![run_length(SymbolTypeTcc::PacketNotReceived, 4)],
496            recv_deltas: vec![],
497            ..Default::default()
498        };
499
500        assert_eq!(
501            vec![65534, 65535, 0, 1],
502            convert_twcc(&feedback)
503                .iter()
504                .map(|ack| ack.sequence_number)
505                .collect::<Vec<_>>()
506        );
507    }
508
509    #[test]
510    fn an_empty_feedback_converts_to_nothing() {
511        let feedback = TransportLayerCc::default();
512        assert!(convert_twcc(&feedback).is_empty());
513    }
514
515    // ---------------------------------------------------------------------------------------
516    // RFC 8888
517    // ---------------------------------------------------------------------------------------
518
519    fn metric(received: bool, offset: u16, ecn: Ecn) -> CcFeedbackMetricBlock {
520        CcFeedbackMetricBlock {
521            received,
522            ecn,
523            arrival_time_offset: offset,
524        }
525    }
526
527    #[test]
528    fn a_ccfb_report_converts_per_stream() {
529        let feedback = CcFeedbackReport {
530            sender_ssrc: 1,
531            report_blocks: vec![
532                CcFeedbackReportBlock {
533                    media_ssrc: 10,
534                    begin_sequence: 100,
535                    metric_blocks: vec![
536                        metric(true, 512, Ecn::NotEct),
537                        metric(false, 0, Ecn::NotEct),
538                    ],
539                },
540                CcFeedbackReportBlock {
541                    media_ssrc: 20,
542                    begin_sequence: 5,
543                    metric_blocks: vec![metric(true, 256, Ecn::Ce)],
544                },
545            ],
546            report_timestamp: 0,
547        };
548
549        let (_, per_stream) = convert_ccfb(&feedback);
550
551        let first = &per_stream[&10];
552        assert_eq!(100, first[0].sequence_number);
553        assert!(!first[1].arrived);
554
555        let second = &per_stream[&20];
556        assert_eq!(5, second[0].sequence_number);
557        assert_eq!(Ecn::Ce, second[0].ecn, "ECN survives conversion");
558
559        // The arrival time is the report timestamp minus the offset: the packet with the
560        // smaller offset (256/1024 s) arrived a quarter of a second after the other.
561        assert_eq!(
562            Duration::from_millis(250),
563            second[0].arrival.unwrap() - first[0].arrival.unwrap()
564        );
565    }
566
567    fn one_packet_report(report_timestamp: u32, offset: u16, sequence: u16) -> CcFeedbackReport {
568        CcFeedbackReport {
569            sender_ssrc: 1,
570            report_blocks: vec![CcFeedbackReportBlock {
571                media_ssrc: 10,
572                begin_sequence: sequence,
573                metric_blocks: vec![metric(true, offset, Ecn::NotEct)],
574            }],
575            report_timestamp,
576        }
577    }
578
579    /// RFC 8888 section 3.1: the arrival time is "an offset before the time represented by the
580    /// Report Timestamp". Across two reports the arrival of a later packet is later by the
581    /// difference of the timestamps less the difference of the offsets.
582    #[test]
583    fn ccfb_arrivals_are_measured_back_from_each_reports_timestamp() {
584        let mut timeline = FeedbackTimeline::new();
585        // 100 ms apart (6554 units of 1/65536 s); offsets of 10/1024 s and 5/1024 s.
586        let (_, first) = timeline.convert_ccfb(&one_packet_report(0x0001_0000, 10, 1));
587        let (_, second) = timeline.convert_ccfb(&one_packet_report(0x0001_0000 + 6554, 5, 2));
588
589        let gap = second[&10][0].arrival.unwrap() - first[&10][0].arrival.unwrap();
590        let expected = Duration::from_secs_f64(6554.0 / 65536.0 + 5.0 / 1024.0);
591        assert!(
592            gap.abs_diff(expected) < Duration::from_micros(10),
593            "expected {expected:?}, got {gap:?}"
594        );
595    }
596
597    /// The report timestamp wraps every 18.2 hours. The report after the wrap is later, not
598    /// 18 hours earlier.
599    #[test]
600    fn the_ccfb_report_timestamp_is_followed_through_its_wrap() {
601        let mut timeline = FeedbackTimeline::new();
602        let (_, before) = timeline.convert_ccfb(&one_packet_report(0xFFFF_F000, 0, 1));
603        let (_, after) = timeline.convert_ccfb(&one_packet_report(0x0000_0A00, 0, 2));
604
605        let gap = after[&10][0].arrival.unwrap() - before[&10][0].arrival.unwrap();
606        let expected = Duration::from_secs_f64(f64::from(0x1000u32 + 0xA00) / 65536.0);
607        assert!(
608            gap.abs_diff(expected) < Duration::from_micros(10),
609            "expected {expected:?}, got {gap:?}"
610        );
611    }
612
613    fn one_packet_feedback(reference_time: u32, sequence: u16) -> TransportLayerCc {
614        TransportLayerCc {
615            base_sequence_number: sequence,
616            packet_status_count: 1,
617            reference_time,
618            packet_chunks: vec![run_length(SymbolTypeTcc::PacketReceivedSmallDelta, 1)],
619            recv_deltas: vec![RecvDelta {
620                type_tcc_packet: SymbolTypeTcc::PacketReceivedSmallDelta,
621                delta: 0,
622            }],
623            ..Default::default()
624        }
625    }
626
627    /// draft-holmer-rmcat-transport-wide-cc-extensions-01 section 3.1: the reference time is a
628    /// 24-bit value in multiples of 64 ms. It wraps every 12.4 days, and a receiver may start it
629    /// anywhere: the feedback after 0xFFFFFF is 64 ms later, not 12.4 days earlier (audit bug
630    /// T5).
631    #[test]
632    fn the_twcc_reference_time_is_followed_through_its_wrap() {
633        let mut timeline = FeedbackTimeline::new();
634        let before = timeline.convert_twcc(&one_packet_feedback(0x00FF_FFFF, 1));
635        let after = timeline.convert_twcc(&one_packet_feedback(0x0000_0000, 2));
636        let later = timeline.convert_twcc(&one_packet_feedback(0x0000_0002, 3));
637
638        assert_eq!(
639            Duration::from_millis(64),
640            after[0].arrival.unwrap() - before[0].arrival.unwrap()
641        );
642        assert_eq!(
643            Duration::from_millis(128),
644            later[0].arrival.unwrap() - after[0].arrival.unwrap()
645        );
646    }
647
648    /// Feedback read out of order steps the clock back by the difference, not forward by almost
649    /// a whole period.
650    #[test]
651    fn a_reference_time_behind_the_last_one_steps_back() {
652        let mut timeline = FeedbackTimeline::new();
653        let first = timeline.convert_twcc(&one_packet_feedback(10, 1));
654        let earlier = timeline.convert_twcc(&one_packet_feedback(8, 2));
655
656        assert_eq!(
657            Duration::from_millis(128),
658            first[0].arrival.unwrap() - earlier[0].arrival.unwrap()
659        );
660    }
661
662    /// RFC 8888 section 3.1: 0x1FFE is an over-range measurement, not an arrival 8 seconds
663    /// before the report (rfc8888.md bug B7).
664    #[test]
665    fn the_over_range_offset_yields_no_arrival_time() {
666        let (delay, per_stream) = convert_ccfb(&one_packet_report(0x0010_0000, 0x1FFE, 1));
667
668        assert!(per_stream[&10][0].arrived, "it did arrive");
669        assert_eq!(None, per_stream[&10][0].arrival, "when is not known");
670        assert_eq!(Duration::ZERO, delay);
671    }
672
673    /// The receiver's own reporting delay is not network time. Without subtracting it, a round
674    /// trip includes however long the receiver sat on the report before sending it.
675    #[test]
676    fn the_reporting_delay_is_the_gap_to_the_newest_arrival() {
677        let feedback = CcFeedbackReport {
678            sender_ssrc: 1,
679            report_blocks: vec![CcFeedbackReportBlock {
680                media_ssrc: 10,
681                begin_sequence: 0,
682                // 1024 units = 1 s ago, 102 ≈ 100 ms ago. The newest is the smaller offset.
683                metric_blocks: vec![
684                    metric(true, 1024, Ecn::NotEct),
685                    metric(true, 102, Ecn::NotEct),
686                ],
687            }],
688            report_timestamp: 0,
689        };
690
691        let (delay, _) = convert_ccfb(&feedback);
692        assert!(
693            (Duration::from_millis(99)..=Duration::from_millis(101)).contains(&delay),
694            "the newest arrival was ~100 ms before the report, got {delay:?}"
695        );
696    }
697
698    /// The reserved offset means the packet arrived after the report was stamped, so there is no
699    /// usable time — and it must not be taken as the newest arrival either.
700    #[test]
701    fn the_reserved_offset_yields_no_arrival_time() {
702        let feedback = CcFeedbackReport {
703            sender_ssrc: 1,
704            report_blocks: vec![CcFeedbackReportBlock {
705                media_ssrc: 10,
706                begin_sequence: 0,
707                metric_blocks: vec![
708                    metric(true, CCFB_OFFSET_AFTER_REPORT, Ecn::NotEct),
709                    metric(true, 512, Ecn::NotEct),
710                ],
711            }],
712            report_timestamp: 0,
713        };
714
715        let (delay, per_stream) = convert_ccfb(&feedback);
716        assert!(per_stream[&10][0].arrived);
717        assert_eq!(None, per_stream[&10][0].arrival);
718        assert_eq!(
719            Duration::from_millis(500),
720            delay,
721            "the reserved value did not become the newest arrival"
722        );
723    }
724
725    #[test]
726    fn a_report_with_no_arrivals_has_no_reporting_delay() {
727        let feedback = CcFeedbackReport {
728            sender_ssrc: 1,
729            report_blocks: vec![CcFeedbackReportBlock {
730                media_ssrc: 10,
731                begin_sequence: 0,
732                metric_blocks: vec![metric(false, 0, Ecn::NotEct)],
733            }],
734            report_timestamp: 0,
735        };
736
737        let (delay, per_stream) = convert_ccfb(&feedback);
738        assert_eq!(Duration::ZERO, delay);
739        assert!(!per_stream[&10][0].arrived);
740    }
741
742    #[test]
743    fn ccfb_sequence_numbers_wrap_within_a_block() {
744        let feedback = CcFeedbackReport {
745            sender_ssrc: 1,
746            report_blocks: vec![CcFeedbackReportBlock {
747                media_ssrc: 10,
748                begin_sequence: 65535,
749                metric_blocks: vec![metric(false, 0, Ecn::NotEct), metric(false, 0, Ecn::NotEct)],
750            }],
751            report_timestamp: 0,
752        };
753
754        let (_, per_stream) = convert_ccfb(&feedback);
755        assert_eq!(
756            vec![65535, 0],
757            per_stream[&10]
758                .iter()
759                .map(|ack| ack.sequence_number)
760                .collect::<Vec<_>>()
761        );
762    }
763}