Skip to main content

labstream_proto/
dgram.rs

1//! The wire formats of the `dgram/1` feature. `docs/extensions.md`, section
2//! `dgram`.
3//!
4//! Four datagrams go between the two UDP sockets: the hello and the feedback
5//! of the inlet, and the data and idle datagrams of the outlet. Three records
6//! go on the TCP
7//! connection: the path record of the outlet, and the resend request and
8//! path request of the inlet. Each number is little-endian, whatever the
9//! byte order of the connection.
10
11/// The largest datagram, the header included. This size passes most links
12/// with no fragmentation of IP.
13pub const MAX_DATAGRAM: usize = 1200;
14
15/// The length of the header of a data datagram.
16pub const DATA_HEADER: usize = 1 + 8 + 8 + 2 + 4;
17
18/// The largest sample of a stream that can use `dgram/1`. A datagram then
19/// holds at least 3 samples, so the copies can work.
20pub const MAX_SAMPLE_BYTES: usize = 400;
21
22/// The type byte of a hello datagram.
23pub const HELLO: u8 = 1;
24/// The type byte of a data datagram.
25pub const DATA: u8 = 2;
26/// The type byte of an idle datagram.
27pub const IDLE: u8 = 3;
28/// The type byte of a feedback datagram.
29pub const FEEDBACK: u8 = 4;
30/// The type byte of a compressed data datagram (`comp/1` + `dgram/1`).
31pub const DATA_COMP: u8 = 5;
32/// The length of the header of a feedback datagram.
33pub const FEEDBACK_HEADER: usize = 1 + 8 + 4 + 1;
34/// The most gaps in one feedback datagram.
35pub const MAX_GAPS: usize = 64;
36/// The value of `loss` in a feedback datagram when the inlet has no measure.
37pub const NO_MEASURE: u32 = u32::MAX;
38
39/// The first byte of a path record, on TCP from the outlet.
40pub const PATH_TAG: u8 = 0xFD;
41/// The length of a path record.
42pub const PATH_LEN: usize = 1 + 1 + 8;
43/// The first byte of a resend request, on TCP from the inlet.
44pub const RESEND_TAG: u8 = 0xFC;
45/// The length of a resend request.
46pub const RESEND_LEN: usize = 1 + 8 + 4;
47/// The first byte of a path request, on TCP from the inlet.
48pub const PATH_REQUEST_TAG: u8 = 0xFB;
49/// The length of a path request.
50pub const PATH_REQUEST_LEN: usize = 1 + 1 + 8;
51
52/// The path of the samples.
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54pub enum Path {
55    /// The TCP connection.
56    Tcp,
57    /// The UDP socket.
58    Udp,
59}
60
61impl Path {
62    fn byte(self) -> u8 {
63        match self {
64            Path::Tcp => 0,
65            Path::Udp => 1,
66        }
67    }
68
69    fn from_byte(b: u8) -> Option<Path> {
70        match b {
71            0 => Some(Path::Tcp),
72            1 => Some(Path::Udp),
73            _ => None,
74        }
75    }
76}
77
78/// One datagram, as the receiver reads it.
79#[derive(Debug, Clone, Copy, PartialEq, Eq)]
80pub enum Datagram<'a> {
81    /// The first datagram of the inlet.
82    Hello {
83        /// The cookie of the answer.
84        cookie: u64,
85    },
86    /// Samples with consecutive numbers.
87    Data {
88        /// The cookie of the answer.
89        cookie: u64,
90        /// The number of the first sample.
91        first: u64,
92        /// The count of samples.
93        count: u16,
94        /// The number of the datagram.
95        serial: u32,
96        /// The samples, in the encoding of SPEC.md 7.
97        payload: &'a [u8],
98    },
99    /// Compressed samples with consecutive numbers (`comp/1`).
100    DataComp {
101        /// The cookie of the answer.
102        cookie: u64,
103        /// The number of the first sample.
104        first: u64,
105        /// The count of samples.
106        count: u16,
107        /// The number of the datagram.
108        serial: u32,
109        /// Self-contained compressed block decoded by [`crate::comp::decode_dgram_payload`].
110        payload: &'a [u8],
111    },
112    /// No sample follows.
113    Idle {
114        /// The cookie of the answer.
115        cookie: u64,
116        /// The number of the next sample.
117        next: u64,
118    },
119    /// The measured loss and the small gaps of the inlet.
120    Feedback {
121        /// The cookie of the answer.
122        cookie: u64,
123        /// The loss of datagrams in parts per million, or [`NO_MEASURE`].
124        loss: u32,
125        /// The gaps that the inlet asks for.
126        gaps: Gaps<'a>,
127    },
128}
129
130/// The gaps of a feedback datagram, as `(from, count)` pairs.
131#[derive(Debug, Clone, Copy, PartialEq, Eq)]
132pub struct Gaps<'a>(&'a [u8]);
133
134impl Gaps<'_> {
135    /// Each gap, in the order of the datagram.
136    pub fn iter(&self) -> impl Iterator<Item = (u64, u32)> + '_ {
137        self.0
138            .chunks_exact(12)
139            .map(|g| (u64_at(g, 0), u32::from_le_bytes([g[8], g[9], g[10], g[11]])))
140    }
141}
142
143/// Why a datagram could not be read.
144#[derive(Debug, Clone, Copy, PartialEq, Eq)]
145pub enum Error {
146    /// The datagram is shorter than its header.
147    Truncated,
148    /// The type byte is unknown.
149    BadType(u8),
150}
151
152fn u64_at(b: &[u8], at: usize) -> u64 {
153    let mut x = [0u8; 8];
154    x.copy_from_slice(&b[at..at + 8]);
155    u64::from_le_bytes(x)
156}
157
158/// Write a hello datagram.
159pub fn hello(cookie: u64) -> [u8; 9] {
160    let mut out = [0u8; 9];
161    out[0] = HELLO;
162    out[1..].copy_from_slice(&cookie.to_le_bytes());
163    out
164}
165
166/// Write the header of a data datagram. The samples follow it.
167pub fn data_header(out: &mut Vec<u8>, cookie: u64, first: u64, count: u16, serial: u32) {
168    out.push(DATA);
169    out.extend_from_slice(&cookie.to_le_bytes());
170    out.extend_from_slice(&first.to_le_bytes());
171    out.extend_from_slice(&count.to_le_bytes());
172    out.extend_from_slice(&serial.to_le_bytes());
173}
174
175/// Write the header of a compressed data datagram (`DATA_COMP`).
176pub fn data_comp_header(out: &mut Vec<u8>, cookie: u64, first: u64, count: u16, serial: u32) {
177    out.push(DATA_COMP);
178    out.extend_from_slice(&cookie.to_le_bytes());
179    out.extend_from_slice(&first.to_le_bytes());
180    out.extend_from_slice(&count.to_le_bytes());
181    out.extend_from_slice(&serial.to_le_bytes());
182}
183
184/// Write a feedback datagram. Only the first [`MAX_GAPS`] gaps go in.
185pub fn feedback(cookie: u64, loss: u32, gaps: &[(u64, u32)]) -> Vec<u8> {
186    let gaps = &gaps[..gaps.len().min(MAX_GAPS)];
187    let mut out = Vec::with_capacity(FEEDBACK_HEADER + 12 * gaps.len());
188    out.push(FEEDBACK);
189    out.extend_from_slice(&cookie.to_le_bytes());
190    out.extend_from_slice(&loss.to_le_bytes());
191    out.push(gaps.len() as u8);
192    for &(from, count) in gaps {
193        out.extend_from_slice(&from.to_le_bytes());
194        out.extend_from_slice(&count.to_le_bytes());
195    }
196    out
197}
198
199/// Write an idle datagram.
200pub fn idle(cookie: u64, next: u64) -> [u8; 17] {
201    let mut out = [0u8; 17];
202    out[0] = IDLE;
203    out[1..9].copy_from_slice(&cookie.to_le_bytes());
204    out[9..].copy_from_slice(&next.to_le_bytes());
205    out
206}
207
208/// Read one datagram.
209pub fn parse(buf: &[u8]) -> Result<Datagram<'_>, Error> {
210    let kind = *buf.first().ok_or(Error::Truncated)?;
211    match kind {
212        HELLO if buf.len() >= 9 => Ok(Datagram::Hello {
213            cookie: u64_at(buf, 1),
214        }),
215        DATA if buf.len() >= DATA_HEADER => Ok(Datagram::Data {
216            cookie: u64_at(buf, 1),
217            first: u64_at(buf, 9),
218            count: u16::from_le_bytes([buf[17], buf[18]]),
219            serial: u32::from_le_bytes([buf[19], buf[20], buf[21], buf[22]]),
220            payload: &buf[DATA_HEADER..],
221        }),
222        DATA_COMP if buf.len() >= DATA_HEADER => Ok(Datagram::DataComp {
223            cookie: u64_at(buf, 1),
224            first: u64_at(buf, 9),
225            count: u16::from_le_bytes([buf[17], buf[18]]),
226            serial: u32::from_le_bytes([buf[19], buf[20], buf[21], buf[22]]),
227            payload: &buf[DATA_HEADER..],
228        }),
229        IDLE if buf.len() >= 17 => Ok(Datagram::Idle {
230            cookie: u64_at(buf, 1),
231            next: u64_at(buf, 9),
232        }),
233        FEEDBACK if buf.len() >= FEEDBACK_HEADER => {
234            let n = buf[13] as usize;
235            let end = FEEDBACK_HEADER + 12 * n;
236            if buf.len() < end {
237                return Err(Error::Truncated);
238            }
239            Ok(Datagram::Feedback {
240                cookie: u64_at(buf, 1),
241                loss: u32::from_le_bytes([buf[9], buf[10], buf[11], buf[12]]),
242                gaps: Gaps(&buf[FEEDBACK_HEADER..end]),
243            })
244        }
245        HELLO | DATA | DATA_COMP | IDLE | FEEDBACK => Err(Error::Truncated),
246        other => Err(Error::BadType(other)),
247    }
248}
249
250/// Append a path record: the samples from `number` go on `path`.
251pub fn write_path(out: &mut Vec<u8>, path: Path, number: u64) {
252    out.push(PATH_TAG);
253    out.push(path.byte());
254    out.extend_from_slice(&number.to_le_bytes());
255}
256
257/// Append a resend request for `count` samples from `from`.
258pub fn write_resend(out: &mut Vec<u8>, from: u64, count: u32) {
259    out.push(RESEND_TAG);
260    out.extend_from_slice(&from.to_le_bytes());
261    out.extend_from_slice(&count.to_le_bytes());
262}
263
264/// Append a path request: the inlet asks for `path` from the number `from`.
265pub fn write_path_request(out: &mut Vec<u8>, path: Path, from: u64) {
266    out.push(PATH_REQUEST_TAG);
267    out.push(path.byte());
268    out.extend_from_slice(&from.to_le_bytes());
269}
270
271/// A record at the start of a byte stream on TCP.
272#[derive(Debug, Clone, Copy, PartialEq, Eq)]
273pub enum Record {
274    /// A path record, from the outlet.
275    Path {
276        /// The new path.
277        path: Path,
278        /// The number of the first sample on the new path.
279        number: u64,
280    },
281    /// A resend request, from the inlet.
282    Resend {
283        /// The first missing number.
284        from: u64,
285        /// The count of missing samples.
286        count: u32,
287    },
288    /// A path request, from the inlet.
289    PathRequest {
290        /// The path that the inlet asks for.
291        path: Path,
292        /// The number that the inlet expects next.
293        from: u64,
294    },
295    /// A record that is cut. The caller reads more bytes.
296    Incomplete,
297    /// No record of this module.
298    None,
299    /// A record with a path byte that is not 0 or 1.
300    Bad,
301}
302
303impl Record {
304    /// The length of the record in bytes, for a complete record.
305    pub fn len(&self) -> usize {
306        match self {
307            Record::Path { .. } => PATH_LEN,
308            Record::Resend { .. } => RESEND_LEN,
309            Record::PathRequest { .. } => PATH_REQUEST_LEN,
310            _ => 0,
311        }
312    }
313
314    /// True for a record with no bytes.
315    pub fn is_empty(&self) -> bool {
316        self.len() == 0
317    }
318}
319
320/// Look at the start of `buf` for a record of this module.
321pub fn peek(buf: &[u8]) -> Record {
322    let Some(&tag) = buf.first() else {
323        return Record::None;
324    };
325    let need = match tag {
326        PATH_TAG => PATH_LEN,
327        RESEND_TAG => RESEND_LEN,
328        PATH_REQUEST_TAG => PATH_REQUEST_LEN,
329        _ => return Record::None,
330    };
331    if buf.len() < need {
332        return Record::Incomplete;
333    }
334    match tag {
335        PATH_TAG => match Path::from_byte(buf[1]) {
336            Some(path) => Record::Path {
337                path,
338                number: u64_at(buf, 2),
339            },
340            None => Record::Bad,
341        },
342        RESEND_TAG => Record::Resend {
343            from: u64_at(buf, 1),
344            count: u32::from_le_bytes([buf[9], buf[10], buf[11], buf[12]]),
345        },
346        _ => match Path::from_byte(buf[1]) {
347            Some(path) => Record::PathRequest {
348                path,
349                from: u64_at(buf, 2),
350            },
351            None => Record::Bad,
352        },
353    }
354}
355
356/// The most later datagrams that carry a copy of a sample.
357pub const MAX_COPIES: u8 = 8;
358
359/// The count of copies for a measured loss of datagrams, in parts per
360/// million. `docs/extensions.md`, section `dgram`, the copies, rule 6.
361pub fn copies_for(loss_ppm: u32) -> u8 {
362    match loss_ppm {
363        0 => 0,
364        1..=20_000 => 2,
365        20_001..=100_000 => 3,
366        100_001..=250_000 => 4,
367        250_001..=400_000 => 6,
368        _ => MAX_COPIES,
369    }
370}
371
372/// The time that each report must give a lower count of copies before
373/// that count applies.
374pub const LOWER_AFTER: f64 = 5.0;
375/// The count of datagrams that the outlet must send while each report
376/// gives a lower count of copies, before that count applies. At 1 % loss,
377/// 1000 datagrams in a row with no loss occur less than once in 20000. A
378/// stream with few datagrams, for example chunks of 16, thus keeps its
379/// copies.
380pub const LOWER_DATAGRAMS: u32 = 1000;
381
382/// The count of copies of the outlet, from the reports of the inlet. A
383/// higher count applies at once. A lower count applies only after
384/// [`LOWER_AFTER`] seconds and [`LOWER_DATAGRAMS`] datagrams. Time is a
385/// value in seconds that the caller gives.
386#[derive(Debug, Default)]
387pub struct CopyControl {
388    current: u8,
389    /// The start of the time with lower reports (the time and the `serial`
390    /// of the next datagram), and the highest count that they gave.
391    lower: Option<(f64, u32, u8)>,
392}
393
394impl CopyControl {
395    /// A control that starts with no copies.
396    pub fn new() -> CopyControl {
397        CopyControl::default()
398    }
399
400    /// The count of copies now.
401    pub fn copies(&self) -> u8 {
402        self.current
403    }
404
405    /// Take one report. `loss` is in parts per million, or [`NO_MEASURE`].
406    /// `serial` is the `serial` of the next datagram of the outlet. The
407    /// result is the count of copies after the report.
408    pub fn report(&mut self, loss: u32, now: f64, serial: u32) -> u8 {
409        if loss == NO_MEASURE {
410            return self.current;
411        }
412        let target = copies_for(loss);
413        if target >= self.current {
414            self.current = target;
415            self.lower = None;
416            return self.current;
417        }
418        let (since, from, high) = *self.lower.get_or_insert((now, serial, target));
419        let high = high.max(target);
420        if now - since >= LOWER_AFTER && serial.wrapping_sub(from) >= LOWER_DATAGRAMS {
421            self.current = high;
422            // This report starts the next time with lower reports.
423            self.lower = (target < high).then_some((now, serial, target));
424        } else {
425            self.lower = Some((since, from, high));
426        }
427        self.current
428    }
429}
430
431/// The length of one bucket of the loss meter, in seconds.
432const BUCKET: f64 = 0.1;
433/// The count of buckets that the loss meter adds.
434const BUCKETS: usize = 10;
435/// A pause in the datagrams of at least this time is a cut. The jump in
436/// `serial` across it is no loss.
437const CUT: f64 = 1.0;
438
439/// The loss of datagrams at the inlet, from their `serial`.
440/// `docs/extensions.md`, section `dgram`, the feedback datagram, rule 1.
441///
442/// Each jump in `serial` counts as loss, except a jump across a pause of
443/// 1 s or more. A datagram that arrives after a later one takes back one
444/// loss. The meter adds the last 10 buckets of 100 ms.
445#[derive(Debug, Default)]
446pub struct LossMeter {
447    /// (start, datagrams, lost), oldest first.
448    buckets: std::collections::VecDeque<(f64, u64, u64)>,
449    /// The highest `serial`, and the time of the last datagram.
450    last: Option<(u32, f64)>,
451}
452
453impl LossMeter {
454    /// An empty meter.
455    pub fn new() -> LossMeter {
456        LossMeter::default()
457    }
458
459    /// One data datagram arrived at `now`.
460    pub fn record(&mut self, serial: u32, now: f64) {
461        let (mut lost, mut back) = (0u64, false);
462        match self.last {
463            Some((high, at)) if serial > high => {
464                if now - at < CUT {
465                    lost = (serial - high - 1) as u64;
466                }
467                self.last = Some((serial, now));
468            }
469            Some((high, _)) => {
470                back = serial < high;
471                self.last = Some((high, now));
472            }
473            None => self.last = Some((serial, now)),
474        }
475        match self.buckets.back_mut() {
476            Some(b) if now - b.0 < BUCKET => {
477                b.1 += 1;
478                b.2 += lost;
479            }
480            _ => {
481                self.buckets.push_back((now, 1, lost));
482                if self.buckets.len() > BUCKETS {
483                    self.buckets.pop_front();
484                }
485            }
486        }
487        if back {
488            // A late datagram: its loss counted when the later one came.
489            if let Some(b) = self.buckets.iter_mut().rev().find(|b| b.2 > 0) {
490                b.2 -= 1;
491            }
492        }
493    }
494
495    /// The loss in parts per million over the last second, or
496    /// [`NO_MEASURE`] if fewer than 10 datagrams arrived in it.
497    pub fn loss_ppm(&self, now: f64) -> u32 {
498        let (mut got, mut lost) = (0u64, 0u64);
499        for b in &self.buckets {
500            if now - b.0 < BUCKET * BUCKETS as f64 {
501                got += b.1;
502                lost += b.2;
503            }
504        }
505        if got < 10 {
506            return NO_MEASURE;
507        }
508        (lost * 1_000_000 / (got + lost)) as u32
509    }
510}
511
512/// How many sent samples the packer keeps for copies.
513const RECENT: usize = 128;
514
515/// What the outlet sends for a part of a push.
516#[derive(Debug, Clone, PartialEq, Eq)]
517pub enum Packet {
518    /// One data datagram, ready to send.
519    Datagram(Vec<u8>),
520    /// The sample with this number does not fit in one datagram. It goes on
521    /// TCP, with its `seq` record.
522    Tcp(u64),
523}
524
525/// Puts samples into data datagrams, with copies of the samples before
526/// them. `docs/extensions.md`, section `dgram`, the copies.
527///
528/// The packer works on encoded samples, so it needs no codec. Each sample
529/// must carry its full timestamp.
530#[derive(Debug)]
531pub struct Packer {
532    cookie: u64,
533    /// The last samples, with their numbers and the count of copies that
534    /// went out, oldest first. The numbers are consecutive.
535    recent: std::collections::VecDeque<(u64, Vec<u8>, u8)>,
536    /// The count of copies of each sample.
537    copies: u8,
538    /// The `serial` of the next data datagram.
539    serial: u32,
540}
541
542impl Packer {
543    /// A packer for the connection with this cookie. It starts with no
544    /// copies.
545    pub fn new(cookie: u64) -> Packer {
546        Packer {
547            cookie,
548            recent: std::collections::VecDeque::new(),
549            copies: 0,
550            serial: 0,
551        }
552    }
553
554    /// The count of copies of each sample.
555    pub fn copies(&self) -> u8 {
556        self.copies
557    }
558
559    /// The `serial` of the next data datagram.
560    pub fn serial(&self) -> u32 {
561        self.serial
562    }
563
564    /// Set the count of copies of each sample, at most [`MAX_COPIES`].
565    pub fn set_copies(&mut self, copies: u8) {
566        self.copies = copies.min(MAX_COPIES);
567        if self.copies == 0 {
568            self.recent.clear();
569        }
570    }
571
572    /// Put samples of a resend into data datagrams with no copies.
573    /// `samples` holds encoded samples with consecutive numbers from
574    /// `first`. A sample too large for a datagram is left out.
575    pub fn resend(&mut self, first: u64, samples: &[Vec<u8>], out: &mut Vec<Vec<u8>>) {
576        let room = MAX_DATAGRAM - DATA_HEADER;
577        let mut i = 0;
578        while i < samples.len() {
579            if samples[i].len() > room {
580                i += 1;
581                continue;
582            }
583            let mut j = i;
584            let mut used = 0;
585            while j < samples.len() && used + samples[j].len() <= room {
586                used += samples[j].len();
587                j += 1;
588            }
589            let mut d = Vec::with_capacity(DATA_HEADER + used);
590            let serial = self.next_serial();
591            data_header(
592                &mut d,
593                self.cookie,
594                first.wrapping_add(i as u64),
595                (j - i) as u16,
596                serial,
597            );
598            for bytes in &samples[i..j] {
599                d.extend_from_slice(bytes);
600            }
601            out.push(d);
602            i = j;
603        }
604    }
605
606    fn next_serial(&mut self) -> u32 {
607        let s = self.serial;
608        self.serial = self.serial.wrapping_add(1);
609        s
610    }
611
612    /// Put the samples of one push into packets, from slices in one buffer.
613    /// The caller reuses `gram`, and `on_datagram` or `on_tcp` runs for each
614    /// packet. When `copies` is 0, no sample goes into the copy buffer.
615    pub fn push_slices(
616        &mut self,
617        first: u64,
618        samples: &[&[u8]],
619        gram: &mut Vec<u8>,
620        mut on_datagram: impl FnMut(&[u8]),
621        mut on_tcp: impl FnMut(u64),
622    ) {
623        let room = MAX_DATAGRAM - DATA_HEADER;
624        let mut i = 0;
625        while i < samples.len() {
626            let n = first.wrapping_add(i as u64);
627            if samples[i].len() > room {
628                on_tcp(n);
629                self.recent.clear();
630                i += 1;
631                continue;
632            }
633            let mut j = i;
634            let mut used = 0;
635            while j < samples.len() && used + samples[j].len() <= room {
636                used += samples[j].len();
637                j += 1;
638            }
639            let copies = if self.copies == 0 {
640                0
641            } else {
642                self.take_copies(n, room - used)
643            };
644            self.write_datagram(gram, n, copies, &samples[i..j]);
645            on_datagram(gram);
646            if self.copies > 0 {
647                for (k, sample) in samples[i..j].iter().enumerate() {
648                    self.remember(n.wrapping_add(k as u64), sample.to_vec());
649                }
650            }
651            i = j;
652        }
653    }
654
655    /// Put the samples of one push into packets. `samples` holds encoded
656    /// samples with consecutive numbers from `first`.
657    ///
658    /// The new samples fill each datagram first. The free space then takes
659    /// copies of the samples just before them, newest first, so that the
660    /// samples of a datagram stay consecutive. Each sample goes into at most
661    /// `1 + copies` datagrams.
662    pub fn push(&mut self, first: u64, samples: &[Vec<u8>], out: &mut Vec<Packet>) {
663        let room = MAX_DATAGRAM - DATA_HEADER;
664        let mut i = 0;
665        while i < samples.len() {
666            let n = first.wrapping_add(i as u64);
667            if samples[i].len() > room {
668                out.push(Packet::Tcp(n));
669                // A copy must stand just before the new samples, so the
670                // samples before a gap in the run are of no further use.
671                self.recent.clear();
672                i += 1;
673                continue;
674            }
675            let mut j = i;
676            let mut used = 0;
677            while j < samples.len() && used + samples[j].len() <= room {
678                used += samples[j].len();
679                j += 1;
680            }
681            let copies = if self.copies == 0 {
682                0
683            } else {
684                self.take_copies(n, room - used)
685            };
686            out.push(Packet::Datagram(self.datagram(n, copies, &samples[i..j])));
687            if self.copies > 0 {
688                for (k, sample) in samples[i..j].iter().enumerate() {
689                    self.remember(n.wrapping_add(k as u64), sample.clone());
690                }
691            }
692            i = j;
693        }
694    }
695
696    /// A datagram with copies of the last samples and no new sample, or
697    /// `None` when each recent sample has all its copies. The outlet sends
698    /// it when no data datagram follows for 5 ms.
699    pub fn repeat(&mut self) -> Option<Vec<u8>> {
700        let next = self.recent.back()?.0.wrapping_add(1);
701        let copies = self.take_copies(next, MAX_DATAGRAM - DATA_HEADER);
702        if copies == 0 {
703            return None;
704        }
705        Some(self.datagram(next, copies, &[]))
706    }
707
708    /// Mark the copies of the samples just before `next`, newest first,
709    /// that fit in `room` bytes. The result is their count.
710    fn take_copies(&mut self, next: u64, mut room: usize) -> usize {
711        let mut count = 0;
712        let copies = self.copies;
713        for (number, bytes, sent) in self.recent.iter_mut().rev() {
714            if *number != next.wrapping_sub(1 + count as u64)
715                || *sent >= copies
716                || bytes.len() > room
717            {
718                break;
719            }
720            room -= bytes.len();
721            *sent += 1;
722            count += 1;
723        }
724        count
725    }
726
727    /// Build a datagram into `d` from the last `copies` recent samples, then
728    /// the new samples, which start at the number `next`.
729    fn write_datagram(&mut self, d: &mut Vec<u8>, next: u64, copies: usize, new: &[&[u8]]) {
730        let count = copies + new.len();
731        d.clear();
732        let serial = self.next_serial();
733        data_header(
734            d,
735            self.cookie,
736            next.wrapping_sub(copies as u64),
737            count as u16,
738            serial,
739        );
740        let start = self.recent.len() - copies;
741        for (_, bytes, _) in self.recent.range(start..) {
742            d.extend_from_slice(bytes);
743        }
744        for bytes in new {
745            d.extend_from_slice(bytes);
746        }
747        debug_assert!(d.len() <= MAX_DATAGRAM);
748    }
749
750    /// Build a datagram from the last `copies` recent samples, then the new
751    /// samples, which start at the number `next`.
752    fn datagram(&mut self, next: u64, copies: usize, new: &[Vec<u8>]) -> Vec<u8> {
753        let count = copies + new.len();
754        let mut d = Vec::with_capacity(MAX_DATAGRAM);
755        let serial = self.next_serial();
756        data_header(
757            &mut d,
758            self.cookie,
759            next.wrapping_sub(copies as u64),
760            count as u16,
761            serial,
762        );
763        let start = self.recent.len() - copies;
764        for (_, bytes, _) in self.recent.range(start..) {
765            d.extend_from_slice(bytes);
766        }
767        for bytes in new {
768            d.extend_from_slice(bytes);
769        }
770        debug_assert!(d.len() <= MAX_DATAGRAM);
771        d
772    }
773
774    fn remember(&mut self, number: u64, bytes: Vec<u8>) {
775        if let Some(last) = self.recent.back() {
776            if last.0.wrapping_add(1) != number {
777                self.recent.clear();
778            }
779        }
780        self.recent.push_back((number, bytes, 0));
781        if self.recent.len() > RECENT {
782            self.recent.pop_front();
783        }
784    }
785}
786
787/// What the inlet must do for a gap.
788#[derive(Debug, Clone, Copy, PartialEq, Eq)]
789pub enum Action {
790    /// Ask the outlet on TCP for `count` samples from `from`.
791    Request {
792        /// The first missing number.
793        from: u64,
794        /// The count of missing samples.
795        count: u32,
796    },
797    /// The inlet gave up the gap. The samples count as lost.
798    GaveUp {
799        /// The first lost number.
800        from: u64,
801        /// The count of lost samples.
802        count: u64,
803    },
804}
805
806/// Puts the samples of two paths back in the order of their numbers.
807/// `docs/extensions.md`, section `dgram`, the resend and the count on two
808/// paths.
809///
810/// The buffer gives each number once, in order. A gap at the expected
811/// number waits for a copy, then for a resend, then counts as lost. Time is
812/// a value in seconds that the caller gives, so the buffer needs no clock.
813#[derive(Debug)]
814pub struct Reorder<T> {
815    expected: Option<u64>,
816    pending: std::collections::BTreeMap<u64, T>,
817    /// The number after the highest number that the inlet knows of.
818    horizon: Option<u64>,
819    gap_since: Option<f64>,
820    /// The open request: the numbers `from..until`, and the time of the
821    /// request or of the last TCP data.
822    requested: Option<(u64, u64, f64)>,
823    lost: u64,
824    duplicates: u64,
825    /// The largest small gap, or 0 when the small gaps go on TCP too.
826    small: u64,
827    /// The time after which the inlet gives up a small gap at the expected
828    /// number.
829    small_give_up: f64,
830    /// The small gaps, in the order of their numbers.
831    holes: Vec<Hole>,
832    /// The round trip of a resend on UDP, in seconds.
833    rtt: Option<f64>,
834    /// The expected number when a small gap stood there first, and the time.
835    head: Option<(u64, f64)>,
836    /// The time of the last UDP datagram, when the caller reports it.
837    last_udp: Option<f64>,
838}
839
840/// One small gap. `docs/extensions.md`, section `dgram`, the resend.
841#[derive(Debug, Clone, Copy, PartialEq)]
842struct Hole {
843    from: u64,
844    until: u64,
845    /// The time when the gap first showed.
846    since: f64,
847    /// The time of the last request.
848    asked: Option<f64>,
849    /// The time of the first request, while it is the only one.
850    first_ask: Option<f64>,
851}
852
853/// The round trip of a resend before the first measure, in seconds.
854const FIRST_RTT: f64 = 0.050;
855/// The shortest time between two requests for one small gap, in seconds.
856const MIN_REPEAT: f64 = 0.010;
857/// A small gap is given up only while datagrams arrive within this time.
858const UDP_ALIVE: f64 = 0.5;
859/// After this time with no datagram, the link is in a cut, and the wait of
860/// a small gap at `E` starts again when datagrams return.
861const UDP_CUT: f64 = 1.5;
862
863impl<T> Default for Reorder<T> {
864    fn default() -> Self {
865        Reorder {
866            expected: None,
867            pending: std::collections::BTreeMap::new(),
868            horizon: None,
869            gap_since: None,
870            requested: None,
871            lost: 0,
872            duplicates: 0,
873            small: 0,
874            small_give_up: 0.0,
875            holes: Vec::new(),
876            rtt: None,
877            head: None,
878            last_udp: None,
879        }
880    }
881}
882
883impl<T> Reorder<T> {
884    /// An empty buffer with no expected number.
885    pub fn new() -> Self {
886        Reorder::default()
887    }
888
889    /// Set the expected number, if the buffer has none yet.
890    pub fn start(&mut self, number: u64) {
891        if self.expected.is_none() {
892            self.expected = Some(number);
893        }
894    }
895
896    /// Repair each gap of at most `max` samples on UDP: [`Reorder::nacks`]
897    /// gives them, [`Reorder::poll`] asks for none of them on TCP, and gives
898    /// one up at the expected number `give_up` seconds after it showed.
899    pub fn set_small_gaps(&mut self, max: u64, give_up: f64) {
900        self.small = max;
901        self.small_give_up = give_up;
902    }
903
904    /// The round trip of a resend on UDP, once measured.
905    pub fn rtt(&self) -> Option<f64> {
906        self.rtt
907    }
908
909    /// The gaps below the highest known number, as `from..until`, in order.
910    fn gaps(&self) -> Vec<(u64, u64)> {
911        let mut out = Vec::new();
912        let Some(mut at) = self.expected else {
913            return out;
914        };
915        for &n in self.pending.keys() {
916            if n > at {
917                out.push((at, n));
918            }
919            at = n.wrapping_add(1);
920        }
921        if let Some(h) = self.horizon {
922            if h > at {
923                out.push((at, h));
924            }
925        }
926        out
927    }
928
929    /// Find the small gaps again, and keep the times of the old ones. A gap
930    /// that the open TCP request covers is not a small gap.
931    fn update_holes(&mut self, now: f64) {
932        let covered = self.requested.map(|(f, u, _)| (f, u));
933        let old = std::mem::take(&mut self.holes);
934        let gaps = self.gaps();
935        for &(from, until) in &gaps {
936            if until - from > self.small {
937                continue;
938            }
939            if covered.is_some_and(|(f, u)| from >= f && until <= u) {
940                continue;
941            }
942            let mut hole = Hole {
943                from,
944                until,
945                since: now,
946                asked: None,
947                first_ask: None,
948            };
949            let mut overlaps = 0;
950            for o in old.iter().filter(|o| o.from < until && from < o.until) {
951                overlaps += 1;
952                hole.since = hole.since.min(o.since);
953                hole.asked = match (hole.asked, o.asked) {
954                    (Some(a), Some(b)) => Some(a.max(b)),
955                    (a, b) => a.or(b),
956                };
957                // The answer to the first request filled a part of the gap.
958                if o.first_ask.is_some() && (o.from, o.until) == (from, until) {
959                    hole.first_ask = o.first_ask;
960                }
961            }
962            if overlaps > 1 {
963                hole.first_ask = None;
964            }
965            self.holes.push(hole);
966        }
967        // A gap that got smaller or closed after its first request gives a
968        // measure of the round trip.
969        for o in &old {
970            let Some(t) = o.first_ask else { continue };
971            let still: u64 = gaps
972                .iter()
973                .map(|&(f, u)| u.min(o.until).saturating_sub(f.max(o.from)))
974                .sum();
975            if still < o.until - o.from {
976                let sample = now - t;
977                self.rtt = Some(match self.rtt {
978                    None => sample,
979                    Some(r) => 0.875 * r + 0.125 * sample,
980                });
981            }
982        }
983    }
984
985    /// True when the buffer holds a sample above the expected number, or knows
986    /// of a sample above it.
987    pub fn has_gaps(&self) -> bool {
988        !self.pending.is_empty() || self.expected.zip(self.horizon).is_some_and(|(e, h)| h > e)
989    }
990
991    /// The small gaps to ask for on UDP now: each gap that stayed for
992    /// `wait` seconds, again each `max(10 ms, 1.5 x round trip)` until it
993    /// closes. At most [`MAX_GAPS`] gaps, from the lowest.
994    pub fn nacks(&mut self, now: f64, wait: f64) -> Vec<(u64, u32)> {
995        if self.small == 0 || (self.holes.is_empty() && !self.has_gaps()) {
996            return Vec::new();
997        }
998        self.update_holes(now);
999        let every = MIN_REPEAT.max(1.5 * self.rtt.unwrap_or(FIRST_RTT));
1000        let mut out = Vec::new();
1001        for h in self.holes.iter_mut() {
1002            if out.len() == MAX_GAPS {
1003                break;
1004            }
1005            if now - h.since < wait {
1006                continue;
1007            }
1008            if h.asked.is_some_and(|t| now - t < every) {
1009                continue;
1010            }
1011            h.first_ask = if h.asked.is_none() { Some(now) } else { None };
1012            h.asked = Some(now);
1013            out.push((h.from, (h.until - h.from) as u32));
1014        }
1015        out
1016    }
1017
1018    /// The number that the buffer gives next.
1019    pub fn expected(&self) -> Option<u64> {
1020        self.expected
1021    }
1022
1023    /// The count of numbers that the buffer gave up.
1024    pub fn lost(&self) -> u64 {
1025        self.lost
1026    }
1027
1028    /// The count of samples that arrived again, or too late.
1029    pub fn duplicates(&self) -> u64 {
1030        self.duplicates
1031    }
1032
1033    /// Take one sample from either path. When the sample is next in order and
1034    /// no sample waits in the buffer, it goes directly to `out`.
1035    pub fn insert_or_emit(&mut self, number: u64, item: T, out: &mut Vec<T>) -> bool {
1036        if self.expected == Some(number) && self.pending.is_empty() {
1037            out.push(item);
1038            let after = number.wrapping_add(1);
1039            self.expected = Some(after);
1040            self.horizon = Some(self.horizon.map_or(after, |h| h.max(after)));
1041            return true;
1042        }
1043        self.insert(number, item)
1044    }
1045
1046    /// Take one sample from either path. The result is false for a sample
1047    /// that the buffer already has, or that it gave up.
1048    pub fn insert(&mut self, number: u64, item: T) -> bool {
1049        let below = self.expected.is_some_and(|e| number < e);
1050        if below || self.pending.contains_key(&number) {
1051            self.duplicates += 1;
1052            return false;
1053        }
1054        self.pending.insert(number, item);
1055        let after = number.wrapping_add(1);
1056        self.horizon = Some(self.horizon.map_or(after, |h| h.max(after)));
1057        true
1058    }
1059
1060    /// An idle datagram: the next sample of the outlet gets `next`.
1061    pub fn idle(&mut self, next: u64) {
1062        self.horizon = Some(self.horizon.map_or(next, |h| h.max(next)));
1063    }
1064
1065    /// A datagram arrived on UDP at `now`. A small gap is given up only while
1066    /// datagrams still arrive, so a cut does not drop a sample before
1067    /// `resume/1` can ask for it.
1068    pub fn udp_heard(&mut self, now: f64) {
1069        self.last_udp = Some(now);
1070    }
1071
1072    /// The outlet has no sample below `number` for this inlet: a resend
1073    /// started at `number`. The numbers from the expected number up to it
1074    /// count as lost. `docs/extensions.md`, resend rule 5.
1075    pub fn lost_below(&mut self, number: u64) {
1076        if let Some(e) = self.expected {
1077            if number > e {
1078                let given_up = (e..number)
1079                    .filter(|n| !self.pending.contains_key(n))
1080                    .count();
1081                self.lost += given_up as u64;
1082                self.pending = self.pending.split_off(&number);
1083                self.expected = Some(number);
1084            }
1085        }
1086    }
1087
1088    /// Data arrived on TCP at `now`. A resend can be slow on a slow link, so
1089    /// the time limit of an open request counts again from this point.
1090    /// `docs/extensions.md`, section `dgram`, resend rule 6.
1091    pub fn progress(&mut self, now: f64) {
1092        if let Some((from, until, _)) = self.requested {
1093            self.requested = Some((from, until, now));
1094        }
1095    }
1096
1097    /// The numbers `from..until` are on the way on TCP, as at the start of a
1098    /// connection with a `resume` resend. The buffer asks for none of them.
1099    pub fn assume_requested(&mut self, from: u64, until: u64, now: f64) {
1100        if until > from {
1101            self.requested = Some((from, until, now));
1102        }
1103    }
1104
1105    /// Move each sample that follows the expected number to `out`, in
1106    /// order. The result is their count.
1107    pub fn drain(&mut self, out: &mut Vec<T>) -> usize {
1108        let Some(mut e) = self.expected else {
1109            return 0;
1110        };
1111        let mut count = 0;
1112        while let Some(item) = self.pending.remove(&e) {
1113            out.push(item);
1114            e = e.wrapping_add(1);
1115            count += 1;
1116        }
1117        self.expected = Some(e);
1118        count
1119    }
1120
1121    /// The end of the gap at the expected number, or `None` with no gap.
1122    fn gap_end(&self) -> Option<u64> {
1123        let e = self.expected?;
1124        match self.pending.keys().next() {
1125            Some(&first) if first > e => Some(first),
1126            Some(_) => None,
1127            None => self.horizon.filter(|&h| h > e),
1128        }
1129    }
1130
1131    /// Check the gap at the expected number. Call it after each
1132    /// [`Reorder::drain`].
1133    ///
1134    /// A gap that stays for `wait` seconds gives a request. A request with no
1135    /// answer for `give_up` seconds gives up the gap: its numbers count as
1136    /// lost, and the samples after it can go.
1137    pub fn poll(&mut self, now: f64, wait: f64, give_up: f64) -> Option<Action> {
1138        // A request that the expected number passed is complete.
1139        if let (Some((_, until, _)), Some(e)) = (self.requested, self.expected) {
1140            if until <= e {
1141                self.requested = None;
1142                self.gap_since = None;
1143            }
1144        }
1145        let (Some(e), Some(end)) = (self.expected, self.gap_end()) else {
1146            self.gap_since = None;
1147            return None;
1148        };
1149        // A small gap at the expected number is repaired on UDP. Its time
1150        // limit counts from when it reached the expected number: a gap
1151        // behind a TCP resend waits for that resend first. The limit is at
1152        // least 4 round trips, for a link with a long queue.
1153        let in_request = self.requested.is_some_and(|(f, u, _)| e >= f && e < u);
1154        if self.small > 0 && end - e <= self.small && !in_request {
1155            self.gap_since = None;
1156            if let Some(u) = self.last_udp {
1157                if now - u >= UDP_CUT {
1158                    self.head = None;
1159                    return None;
1160                }
1161                if now - u >= UDP_ALIVE {
1162                    return None;
1163                }
1164            }
1165            if self.head.map(|h| h.0) != Some(e) {
1166                self.head = Some((e, now));
1167            }
1168            let since = self.head.map_or(now, |h| h.1);
1169            let limit = self.small_give_up.max(4.0 * self.rtt.unwrap_or(0.0));
1170            if now - since >= limit {
1171                self.lost += end - e;
1172                self.expected = Some(end);
1173                self.holes.retain(|h| h.from != e);
1174                self.head = None;
1175                return Some(Action::GaveUp {
1176                    from: e,
1177                    count: end - e,
1178                });
1179            }
1180            return None;
1181        }
1182        match self.requested {
1183            // The open request covers the start of the gap. No new request
1184            // for that part: the answer can be on the way. A part beyond the
1185            // request gets its own request after the wait.
1186            Some((from, until, at)) => {
1187                if now - at >= give_up {
1188                    let stop = end.min(until);
1189                    self.lost += stop - e;
1190                    self.expected = Some(stop);
1191                    self.requested = None;
1192                    self.gap_since = None;
1193                    return Some(Action::GaveUp {
1194                        from: e,
1195                        count: stop - e,
1196                    });
1197                }
1198                if end > until {
1199                    let since = *self.gap_since.get_or_insert(now);
1200                    if now - since >= wait {
1201                        self.requested = Some((from, end, now));
1202                        self.gap_since = None;
1203                        return Some(Action::Request {
1204                            from: until,
1205                            count: (end - until).min(u32::MAX as u64) as u32,
1206                        });
1207                    }
1208                }
1209                None
1210            }
1211            None => {
1212                let since = *self.gap_since.get_or_insert(now);
1213                if now - since >= wait {
1214                    self.requested = Some((e, end, now));
1215                    self.gap_since = None;
1216                    Some(Action::Request {
1217                        from: e,
1218                        count: (end - e).min(u32::MAX as u64) as u32,
1219                    })
1220                } else {
1221                    None
1222                }
1223            }
1224        }
1225    }
1226}
1227
1228#[cfg(test)]
1229mod tests {
1230    use super::*;
1231
1232    #[test]
1233    fn each_datagram_reads_back() {
1234        assert_eq!(
1235            parse(&hello(0x0102_0304_0506_0708)),
1236            Ok(Datagram::Hello {
1237                cookie: 0x0102_0304_0506_0708
1238            })
1239        );
1240        assert_eq!(
1241            parse(&idle(7, 99)),
1242            Ok(Datagram::Idle {
1243                cookie: 7,
1244                next: 99
1245            })
1246        );
1247        let mut d = Vec::new();
1248        data_header(&mut d, 7, 1000, 2, 9);
1249        d.extend_from_slice(&[1, 2, 3]);
1250        assert_eq!(d.len(), DATA_HEADER + 3);
1251        assert_eq!(
1252            parse(&d),
1253            Ok(Datagram::Data {
1254                cookie: 7,
1255                first: 1000,
1256                count: 2,
1257                serial: 9,
1258                payload: &[1, 2, 3]
1259            })
1260        );
1261    }
1262
1263    #[test]
1264    fn the_numbers_are_little_endian() {
1265        assert_eq!(hello(1)[1..], [1, 0, 0, 0, 0, 0, 0, 0]);
1266        let mut d = Vec::new();
1267        data_header(&mut d, 0, 0x0102, 0x0304, 0x0506_0708);
1268        assert_eq!(d[9..19], [2, 1, 0, 0, 0, 0, 0, 0, 4, 3]);
1269        assert_eq!(d[19..23], [8, 7, 6, 5]);
1270    }
1271
1272    #[test]
1273    fn a_cut_or_unknown_datagram_is_an_error() {
1274        assert_eq!(parse(&[]), Err(Error::Truncated));
1275        assert_eq!(parse(&hello(5)[..8]), Err(Error::Truncated));
1276        assert_eq!(parse(&idle(5, 6)[..16]), Err(Error::Truncated));
1277        let mut d = Vec::new();
1278        data_header(&mut d, 1, 2, 3, 4);
1279        assert_eq!(parse(&d[..DATA_HEADER - 1]), Err(Error::Truncated));
1280        assert_eq!(parse(&[9, 0, 0]), Err(Error::BadType(9)));
1281    }
1282
1283    #[test]
1284    fn each_record_reads_back() {
1285        let mut b = Vec::new();
1286        write_path(&mut b, Path::Udp, 42);
1287        write_resend(&mut b, 100, 7);
1288        write_path_request(&mut b, Path::Tcp, 200);
1289        let first = peek(&b);
1290        assert_eq!(
1291            first,
1292            Record::Path {
1293                path: Path::Udp,
1294                number: 42
1295            }
1296        );
1297        let rest = &b[first.len()..];
1298        let second = peek(rest);
1299        assert_eq!(
1300            second,
1301            Record::Resend {
1302                from: 100,
1303                count: 7
1304            }
1305        );
1306        let rest = &rest[second.len()..];
1307        let third = peek(rest);
1308        assert_eq!(
1309            third,
1310            Record::PathRequest {
1311                path: Path::Tcp,
1312                from: 200
1313            }
1314        );
1315        assert_eq!(rest.len(), third.len());
1316    }
1317
1318    #[test]
1319    fn a_cut_record_asks_for_more_bytes() {
1320        let mut b = Vec::new();
1321        write_resend(&mut b, 1, 2);
1322        for cut in 1..RESEND_LEN {
1323            assert_eq!(peek(&b[..cut]), Record::Incomplete);
1324        }
1325        assert_eq!(peek(&[]), Record::None);
1326        // A sample tag and the `seq` tag are not records of this module.
1327        assert_eq!(peek(&[1, 0]), Record::None);
1328        assert_eq!(peek(&[0xFE, 0]), Record::None);
1329        assert_eq!(peek(&[PATH_TAG, 7, 0, 0, 0, 0, 0, 0, 0, 0]), Record::Bad);
1330    }
1331
1332    #[test]
1333    fn the_tags_differ_from_the_sample_tags_and_the_seq_tag() {
1334        for tag in [PATH_TAG, RESEND_TAG, PATH_REQUEST_TAG] {
1335            assert!(tag != 1 && tag != 2 && tag != crate::seq::TAG);
1336        }
1337    }
1338
1339    // The packer.
1340
1341    /// A sample of `len` bytes whose bytes all hold the low byte of `n`.
1342    fn sample(n: u64, len: usize) -> Vec<u8> {
1343        vec![n as u8; len]
1344    }
1345
1346    /// The numbers in each datagram of `out`, for samples of `len` bytes.
1347    fn numbers(out: &[Packet], len: usize) -> Vec<Vec<u64>> {
1348        out.iter()
1349            .filter_map(|p| match p {
1350                Packet::Datagram(d) => Some(d),
1351                Packet::Tcp(_) => None,
1352            })
1353            .map(|d| {
1354                assert!(d.len() <= MAX_DATAGRAM);
1355                match parse(d).unwrap() {
1356                    Datagram::Data {
1357                        cookie,
1358                        first,
1359                        count,
1360                        payload,
1361                        ..
1362                    } => {
1363                        assert_eq!(cookie, 77);
1364                        assert_eq!(payload.len(), count as usize * len);
1365                        let ns: Vec<u64> = (0..count as u64).map(|k| first + k).collect();
1366                        // Each sample holds the low byte of its number.
1367                        for (k, n) in ns.iter().enumerate() {
1368                            assert_eq!(payload[k * len], *n as u8, "sample {n}");
1369                        }
1370                        ns
1371                    }
1372                    other => panic!("not a data datagram: {other:?}"),
1373                }
1374            })
1375            .collect()
1376    }
1377
1378    /// Push `total` samples of `len` bytes in chunks of `chunk`. With
1379    /// `repeat`, a repeat datagram follows each push.
1380    fn run(total: u64, chunk: u64, len: usize, repeat: bool) -> Vec<Vec<u64>> {
1381        let mut p = Packer::new(77);
1382        p.set_copies(2);
1383        let mut out = Vec::new();
1384        let mut n = 0;
1385        while n < total {
1386            let block: Vec<Vec<u8>> = (n..(n + chunk).min(total))
1387                .map(|k| sample(k, len))
1388                .collect();
1389            p.push(n, &block, &mut out);
1390            if repeat {
1391                if let Some(d) = p.repeat() {
1392                    out.push(Packet::Datagram(d));
1393                }
1394            }
1395            n += chunk;
1396        }
1397        numbers(&out, len)
1398    }
1399
1400    #[test]
1401    fn each_sample_goes_into_at_most_three_datagrams() {
1402        for (chunk, len, repeat) in [
1403            (1, 41, false),
1404            (16, 41, true),
1405            (32, 265, true),
1406            (5, 300, true),
1407        ] {
1408            let grams = run(2000, chunk, len, repeat);
1409            let mut seen = std::collections::HashMap::new();
1410            for g in &grams {
1411                for n in g {
1412                    *seen.entry(*n).or_insert(0) += 1;
1413                }
1414            }
1415            assert_eq!(seen.len(), 2000, "each sample goes out");
1416            assert!(seen.values().all(|&c| c <= 3), "chunk {chunk}, len {len}");
1417        }
1418    }
1419
1420    /// The numbers that no datagram carries when the datagram `lost` is
1421    /// lost. The last two samples have no later datagram, so they do not
1422    /// count.
1423    fn missing_without(grams: &[Vec<u64>], lost: usize, total: u64) -> Vec<u64> {
1424        let mut have = std::collections::HashSet::new();
1425        for (k, g) in grams.iter().enumerate() {
1426            if k != lost {
1427                have.extend(g.iter().copied());
1428            }
1429        }
1430        (0..total - 2).filter(|n| !have.contains(n)).collect()
1431    }
1432
1433    #[test]
1434    fn one_lost_datagram_costs_no_sample_at_512_hz_x_8_channels() {
1435        // One sample of 41 bytes in each push.
1436        let grams = run(300, 1, 41, false);
1437        for lost in 0..grams.len() {
1438            assert_eq!(
1439                missing_without(&grams, lost, 300),
1440                Vec::<u64>::new(),
1441                "lost {lost}"
1442            );
1443        }
1444    }
1445
1446    #[test]
1447    fn a_repeat_datagram_covers_a_lost_chunk() {
1448        // Chunks of 16 samples of 41 bytes, and a repeat after each push.
1449        let grams = run(320, 16, 41, true);
1450        for lost in 0..grams.len() {
1451            assert_eq!(
1452                missing_without(&grams, lost, 320),
1453                Vec::<u64>::new(),
1454                "lost {lost}"
1455            );
1456        }
1457    }
1458
1459    #[test]
1460    fn large_samples_fill_a_datagram_with_four() {
1461        let grams = run(64, 32, 265, false);
1462        // 32 new samples of 265 bytes need 8 datagrams of 4 samples.
1463        assert_eq!(grams.len(), 16);
1464        assert!(grams.iter().all(|g| g.len() <= 4));
1465    }
1466
1467    #[test]
1468    fn a_sample_too_large_for_a_datagram_goes_on_tcp() {
1469        let mut p = Packer::new(77);
1470        p.set_copies(2);
1471        let mut out = Vec::new();
1472        let block = vec![sample(0, 41), sample(1, 41), sample(2, 2000), sample(3, 41)];
1473        p.push(0, &block, &mut out);
1474        assert_eq!(out.len(), 3);
1475        assert_eq!(out[1], Packet::Tcp(2));
1476        let grams = numbers(&out, 41);
1477        assert_eq!(
1478            grams,
1479            vec![vec![0, 1], vec![3]],
1480            "no copy crosses the TCP sample"
1481        );
1482    }
1483
1484    #[test]
1485    fn a_repeat_with_nothing_to_copy_is_none() {
1486        let mut p = Packer::new(77);
1487        p.set_copies(2);
1488        assert_eq!(p.repeat(), None);
1489        let mut out = Vec::new();
1490        p.push(0, &[sample(0, 41)], &mut out);
1491        assert!(p.repeat().is_some());
1492        assert!(p.repeat().is_some());
1493        assert_eq!(p.repeat(), None, "each sample has its two copies");
1494    }
1495
1496    // The reorder buffer.
1497
1498    fn take(r: &mut Reorder<u64>) -> Vec<u64> {
1499        let mut out = Vec::new();
1500        r.drain(&mut out);
1501        out
1502    }
1503
1504    #[test]
1505    fn the_buffer_gives_each_number_once_in_order() {
1506        let mut r = Reorder::new();
1507        r.start(10);
1508        assert!(r.insert(12, 12));
1509        assert!(r.insert(10, 10));
1510        assert_eq!(take(&mut r), vec![10]);
1511        assert!(r.insert(11, 11));
1512        assert!(!r.insert(11, 11), "a copy goes away");
1513        assert!(!r.insert(9, 9), "a number below the expected one goes away");
1514        assert_eq!(take(&mut r), vec![11, 12]);
1515        assert_eq!(r.duplicates(), 2);
1516        assert_eq!(r.expected(), Some(13));
1517    }
1518
1519    #[test]
1520    fn a_gap_asks_after_the_wait_and_a_resend_fills_it() {
1521        let mut r = Reorder::new();
1522        r.start(0);
1523        r.insert(0, 0);
1524        r.insert(2, 2);
1525        assert_eq!(take(&mut r), vec![0]);
1526        assert_eq!(r.poll(0.000, 0.010, 0.5), None);
1527        assert_eq!(r.poll(0.005, 0.010, 0.5), None, "a copy can still come");
1528        assert_eq!(
1529            r.poll(0.011, 0.010, 0.5),
1530            Some(Action::Request { from: 1, count: 1 })
1531        );
1532        assert_eq!(r.poll(0.020, 0.010, 0.5), None, "one request for a gap");
1533        // The resend arrives on TCP.
1534        r.insert(1, 1);
1535        assert_eq!(take(&mut r), vec![1, 2]);
1536        assert_eq!(r.poll(0.030, 0.010, 0.5), None);
1537        assert_eq!(r.lost(), 0);
1538    }
1539
1540    #[test]
1541    fn a_gap_with_no_answer_counts_as_lost() {
1542        let mut r = Reorder::new();
1543        r.start(0);
1544        r.insert(3, 3);
1545        assert_eq!(r.poll(0.0, 0.01, 0.5), None);
1546        assert_eq!(
1547            r.poll(0.02, 0.01, 0.5),
1548            Some(Action::Request { from: 0, count: 3 })
1549        );
1550        assert_eq!(r.poll(0.30, 0.01, 0.5), None);
1551        assert_eq!(
1552            r.poll(0.53, 0.01, 0.5),
1553            Some(Action::GaveUp { from: 0, count: 3 })
1554        );
1555        assert_eq!(take(&mut r), vec![3]);
1556        assert_eq!(r.lost(), 3);
1557        assert!(!r.insert(1, 1), "a late sample of the gap goes away");
1558    }
1559
1560    #[test]
1561    fn data_on_tcp_holds_off_the_give_up() {
1562        let mut r = Reorder::new();
1563        r.start(0);
1564        r.insert(3, 3);
1565        assert_eq!(r.poll(0.0, 0.01, 0.5), None);
1566        assert_eq!(
1567            r.poll(0.02, 0.01, 0.5),
1568            Some(Action::Request { from: 0, count: 3 })
1569        );
1570        // The resend is slow: other TCP data arrives at 0.4 and 0.8 s.
1571        r.progress(0.4);
1572        assert_eq!(r.poll(0.6, 0.01, 0.5), None);
1573        r.progress(0.8);
1574        assert_eq!(r.poll(1.2, 0.01, 0.5), None);
1575        // The gap fills at 1.25 s.
1576        for n in 0..3 {
1577            r.insert(n, n);
1578        }
1579        assert_eq!(take(&mut r), vec![0, 1, 2, 3]);
1580        assert_eq!(r.lost(), 0);
1581        // With no data, the limit still acts.
1582        r.insert(6, 6);
1583        assert!(r.poll(2.0, 0.01, 0.5).is_none());
1584        assert!(r.poll(2.02, 0.01, 0.5).is_some());
1585        assert_eq!(
1586            r.poll(2.53, 0.01, 0.5),
1587            Some(Action::GaveUp { from: 4, count: 2 })
1588        );
1589    }
1590
1591    #[test]
1592    fn an_idle_datagram_shows_a_lost_last_sample() {
1593        let mut r = Reorder::new();
1594        r.start(0);
1595        r.insert(0, 0);
1596        assert_eq!(take(&mut r), vec![0]);
1597        assert_eq!(r.poll(0.0, 0.01, 0.5), None, "no gap is known");
1598        r.idle(2);
1599        assert_eq!(r.poll(0.1, 0.01, 0.5), None);
1600        assert_eq!(
1601            r.poll(0.2, 0.01, 0.5),
1602            Some(Action::Request { from: 1, count: 1 })
1603        );
1604    }
1605
1606    #[test]
1607    fn a_history_that_holds_less_counts_the_rest_as_lost() {
1608        let mut r = Reorder::new();
1609        r.start(0);
1610        r.insert(5, 5);
1611        r.insert(8, 8);
1612        // The outlet resends from 4: 0 to 3 are gone.
1613        r.lost_below(4);
1614        r.insert(4, 4);
1615        assert_eq!(take(&mut r), vec![4, 5]);
1616        assert_eq!(r.lost(), 4);
1617    }
1618
1619    #[test]
1620    fn random_loss_and_order_on_two_paths_give_each_number_once() {
1621        // A small random source, so the test needs no crate.
1622        let mut x: u64 = 0x2545_f491_4f6c_dd1d;
1623        let mut rnd = move || {
1624            x ^= x << 13;
1625            x ^= x >> 7;
1626            x ^= x << 17;
1627            x
1628        };
1629        for _ in 0..50 {
1630            let total = 500u64;
1631            let mut r = Reorder::new();
1632            r.start(0);
1633            let mut out = Vec::new();
1634            let mut now = 0.0;
1635            let mut tcp_holds_all = true;
1636            for n in 0..total {
1637                // 20 % of the samples come late, 10 % never on UDP, 5 % twice.
1638                let roll = rnd() % 100;
1639                if roll >= 10 {
1640                    r.insert(n, n);
1641                }
1642                if roll < 5 {
1643                    r.insert(n, n);
1644                }
1645                if roll < 20 && n >= 3 {
1646                    r.insert(n - 3, n - 3);
1647                }
1648                now += 0.002;
1649                r.drain(&mut out);
1650                match r.poll(now, 0.01, 0.5) {
1651                    Some(Action::Request { from, count }) => {
1652                        // The TCP resend gives the samples that half of the
1653                        // time, and nothing the other half.
1654                        if rnd() % 2 == 0 {
1655                            for m in from..from + count as u64 {
1656                                r.insert(m, m);
1657                            }
1658                        } else {
1659                            tcp_holds_all = false;
1660                        }
1661                    }
1662                    Some(Action::GaveUp { .. }) | None => {}
1663                }
1664                r.drain(&mut out);
1665            }
1666            // Let each open gap end.
1667            for _ in 0..1000 {
1668                now += 0.01;
1669                r.drain(&mut out);
1670                let _ = r.poll(now, 0.01, 0.5);
1671            }
1672            r.drain(&mut out);
1673            assert!(out.windows(2).all(|w| w[1] > w[0]), "in order, each once");
1674            let given: std::collections::HashSet<u64> = out.iter().copied().collect();
1675            let last = *out.last().unwrap();
1676            let never = (0..=last).filter(|n| !given.contains(n)).count() as u64;
1677            assert_eq!(r.lost(), never, "lost counts the numbers never given");
1678            if tcp_holds_all {
1679                assert_eq!(r.lost(), 0);
1680            }
1681        }
1682    }
1683
1684    #[test]
1685    fn a_shrinking_gap_gets_no_new_request() {
1686        let mut r = Reorder::new();
1687        r.start(0);
1688        r.insert(100, 100);
1689        assert_eq!(r.poll(0.0, 0.01, 0.5), None);
1690        assert_eq!(
1691            r.poll(0.02, 0.01, 0.5),
1692            Some(Action::Request {
1693                from: 0,
1694                count: 100
1695            })
1696        );
1697        // The answer arrives in parts. The gap shrinks, and stays covered.
1698        for n in 0..40 {
1699            r.insert(n, n);
1700        }
1701        take(&mut r);
1702        r.progress(0.05);
1703        for t in [0.10, 0.20, 0.40] {
1704            assert_eq!(r.poll(t, 0.01, 0.5), None, "at {t}");
1705        }
1706        // The rest of the answer, then a new gap after it.
1707        for n in 40..100 {
1708            r.insert(n, n);
1709        }
1710        r.insert(150, 150);
1711        take(&mut r);
1712        assert_eq!(r.poll(0.41, 0.01, 0.5), None);
1713        assert_eq!(
1714            r.poll(0.43, 0.01, 0.5),
1715            Some(Action::Request {
1716                from: 101,
1717                count: 49
1718            })
1719        );
1720        assert_eq!(r.lost(), 0);
1721    }
1722
1723    #[test]
1724    fn the_range_of_a_resume_resend_gets_no_request() {
1725        let mut r = Reorder::new();
1726        r.start(10);
1727        r.assume_requested(10, 500, 0.0);
1728        // UDP gives 500 onward while TCP still sends the resend.
1729        r.insert(500, 500);
1730        for t in [0.01, 0.1, 0.3] {
1731            assert_eq!(r.poll(t, 0.01, 0.5), None);
1732            r.progress(t);
1733        }
1734        for n in 10..500 {
1735            r.insert(n, n);
1736        }
1737        assert_eq!(take(&mut r).len(), 491);
1738        assert_eq!(r.poll(0.4, 0.01, 0.5), None);
1739        assert_eq!(r.lost(), 0);
1740    }
1741
1742    // The repair on UDP and the count of copies.
1743
1744    #[test]
1745    fn a_feedback_datagram_reads_back() {
1746        let d = feedback(5, 1234, &[(10, 2), (40, 1)]);
1747        assert_eq!(d.len(), FEEDBACK_HEADER + 24);
1748        match parse(&d) {
1749            Ok(Datagram::Feedback { cookie, loss, gaps }) => {
1750                assert_eq!((cookie, loss), (5, 1234));
1751                assert_eq!(gaps.iter().collect::<Vec<_>>(), vec![(10, 2), (40, 1)]);
1752            }
1753            other => panic!("{other:?}"),
1754        }
1755        assert_eq!(parse(&d[..d.len() - 1]), Err(Error::Truncated));
1756        let many: Vec<(u64, u32)> = (0..100).map(|k| (k * 10, 1)).collect();
1757        let d = feedback(5, 0, &many);
1758        assert!(d.len() <= MAX_DATAGRAM);
1759        match parse(&d) {
1760            Ok(Datagram::Feedback { gaps, .. }) => assert_eq!(gaps.iter().count(), MAX_GAPS),
1761            other => panic!("{other:?}"),
1762        }
1763    }
1764
1765    #[test]
1766    fn the_datagrams_get_consecutive_serials() {
1767        let mut p = Packer::new(77);
1768        p.set_copies(2);
1769        let mut out = Vec::new();
1770        p.push(0, &[sample(0, 41)], &mut out);
1771        p.push(1, &[sample(1, 41)], &mut out);
1772        let mut grams: Vec<Vec<u8>> = out
1773            .into_iter()
1774            .map(|p| match p {
1775                Packet::Datagram(d) => d,
1776                Packet::Tcp(_) => panic!("no TCP sample"),
1777            })
1778            .collect();
1779        grams.push(p.repeat().unwrap());
1780        p.resend(0, &[sample(0, 41)], &mut grams);
1781        let serials: Vec<u32> = grams
1782            .iter()
1783            .map(|d| match parse(d) {
1784                Ok(Datagram::Data { serial, .. }) => serial,
1785                other => panic!("{other:?}"),
1786            })
1787            .collect();
1788        assert_eq!(serials, vec![0, 1, 2, 3]);
1789    }
1790
1791    #[test]
1792    fn with_no_copies_each_sample_goes_once_and_a_repeat_is_none() {
1793        let grams = {
1794            let mut p = Packer::new(77);
1795            let mut out = Vec::new();
1796            for n in 0..10 {
1797                p.push(n, &[sample(n, 41)], &mut out);
1798                assert_eq!(p.repeat(), None);
1799            }
1800            numbers(&out, 41)
1801        };
1802        assert_eq!(grams, (0..10).map(|n| vec![n]).collect::<Vec<_>>());
1803    }
1804
1805    #[test]
1806    fn a_resend_packs_the_samples_with_no_copies() {
1807        let mut p = Packer::new(77);
1808        p.set_copies(8);
1809        let block: Vec<Vec<u8>> = (100..140).map(|k| sample(k, 41)).collect();
1810        let mut grams = Vec::new();
1811        p.resend(100, &block, &mut grams);
1812        let out: Vec<Packet> = grams.into_iter().map(Packet::Datagram).collect();
1813        let got: Vec<u64> = numbers(&out, 41).concat();
1814        assert_eq!(got, (100..140).collect::<Vec<_>>());
1815    }
1816
1817    #[test]
1818    fn the_copies_follow_the_loss_up_at_once_and_down_after_5_s() {
1819        // A report at `t` seconds, with 1000 datagrams each second.
1820        let at = |c: &mut CopyControl, loss: u32, t: f64| c.report(loss, t, (t * 1000.0) as u32);
1821        let mut c = CopyControl::new();
1822        assert_eq!(c.copies(), 0, "a clean link sends no copy");
1823        assert_eq!(at(&mut c, NO_MEASURE, 0.0), 0);
1824        assert_eq!(at(&mut c, 0, 0.1), 0);
1825        assert_eq!(at(&mut c, 10_000, 0.2), 2, "1 % loss");
1826        assert_eq!(at(&mut c, 300_000, 0.3), 6, "30 % loss, at once");
1827        assert_eq!(at(&mut c, 500_000, 0.4), 8, "50 % loss, at once");
1828        assert_eq!(at(&mut c, 0, 0.5), 8);
1829        assert_eq!(at(&mut c, 200_000, 3.0), 8, "a lower count waits");
1830        assert_eq!(at(&mut c, 0, 5.4), 8);
1831        assert_eq!(
1832            at(&mut c, 0, 5.5),
1833            4,
1834            "after 5 s, the highest count of the lower reports"
1835        );
1836        assert_eq!(at(&mut c, 0, 9.0), 4);
1837        assert_eq!(at(&mut c, 0, 10.6), 0);
1838        assert_eq!(copies_for(20_000), 2);
1839        assert_eq!(copies_for(20_001), 3);
1840        assert_eq!(copies_for(400_001), MAX_COPIES);
1841    }
1842
1843    #[test]
1844    fn with_few_datagrams_the_copies_stay_longer_than_5_s() {
1845        // 64 datagrams each second, as with chunks of 16 at 512 Hz.
1846        let at = |c: &mut CopyControl, loss: u32, t: f64| c.report(loss, t, (t * 64.0) as u32);
1847        let mut c = CopyControl::new();
1848        assert_eq!(at(&mut c, 10_000, 0.0), 2);
1849        let mut t = 0.1;
1850        while t < 15.0 {
1851            assert_eq!(
1852                at(&mut c, 0, t),
1853                2,
1854                "at {t} s, {} datagrams",
1855                (t * 64.0) as u32
1856            );
1857            t += 0.1;
1858        }
1859        assert_eq!(at(&mut c, 0, 15.8), 0, "after 1000 datagrams");
1860    }
1861
1862    #[test]
1863    fn the_loss_meter_counts_the_gaps_in_serial_but_not_a_cut() {
1864        let mut m = LossMeter::new();
1865        assert_eq!(m.loss_ppm(0.0), NO_MEASURE);
1866        // 100 datagrams in 0.2 s, each 5th one lost, also at the border of
1867        // two buckets.
1868        for k in 0..100u32 {
1869            if k % 5 != 3 {
1870                m.record(k, k as f64 * 0.002);
1871            }
1872        }
1873        let loss = m.loss_ppm(0.2);
1874        assert_eq!(loss, 200_000);
1875        // A late datagram takes back its loss.
1876        let mut m = LossMeter::new();
1877        for (i, k) in [0u32, 1, 3, 2, 4, 5, 6, 7, 8, 9, 10]
1878            .into_iter()
1879            .enumerate()
1880        {
1881            m.record(k, 0.01 * i as f64);
1882        }
1883        assert_eq!(m.loss_ppm(0.2), 0);
1884        // A cut of 2 s, then a clean link: the old buckets leave the window,
1885        // and the jump in serial counts as no loss.
1886        let mut m = LossMeter::new();
1887        for k in 0..50u32 {
1888            m.record(k, k as f64 * 0.002);
1889        }
1890        for k in 0..50u32 {
1891            m.record(5000 + k, 2.0 + k as f64 * 0.002);
1892        }
1893        assert_eq!(m.loss_ppm(2.1), 0);
1894    }
1895
1896    #[test]
1897    fn the_small_gaps_are_asked_for_on_udp_in_parallel() {
1898        let mut r = Reorder::new();
1899        r.set_small_gaps(64, 1.0);
1900        r.start(0);
1901        for n in [0, 2, 3, 5, 6, 7, 100] {
1902            r.insert(n, n);
1903        }
1904        assert_eq!(take(&mut r), vec![0]);
1905        assert_eq!(r.nacks(0.000, 0.010), vec![], "a copy can still come");
1906        assert_eq!(r.poll(0.000, 0.010, 0.5), None);
1907        assert_eq!(
1908            r.nacks(0.011, 0.010),
1909            vec![(1, 1), (4, 1)],
1910            "each small gap at once; the large gap 8..100 is not one"
1911        );
1912        assert_eq!(r.poll(0.011, 0.010, 0.5), None, "no request on TCP");
1913        assert_eq!(r.nacks(0.030, 0.010), vec![], "too soon to ask again");
1914        assert_eq!(
1915            r.nacks(0.090, 0.010),
1916            vec![(1, 1), (4, 1)],
1917            "again after 1.5 x 50 ms"
1918        );
1919        // The answer to the second request gives no measure (only the first
1920        // request of a gap counts).
1921        r.insert(1, 1);
1922        let _ = r.nacks(0.100, 0.010);
1923        assert_eq!(r.rtt(), None);
1924        assert_eq!(take(&mut r), vec![1, 2, 3]);
1925        // A gap that stays for 1 s at the expected number is lost.
1926        assert_eq!(r.poll(0.5, 0.010, 0.5), None, "4 is now at E");
1927        assert_eq!(r.poll(1.4, 0.010, 0.5), None);
1928        assert_eq!(
1929            r.poll(1.5, 0.010, 0.5),
1930            Some(Action::GaveUp { from: 4, count: 1 })
1931        );
1932        assert_eq!(take(&mut r), vec![5, 6, 7]);
1933        assert_eq!(r.lost(), 1);
1934    }
1935
1936    #[test]
1937    fn the_first_answer_measures_the_round_trip() {
1938        let mut r = Reorder::new();
1939        r.set_small_gaps(64, 1.0);
1940        r.start(0);
1941        r.insert(0, 0);
1942        r.insert(2, 2);
1943        take(&mut r);
1944        assert_eq!(r.nacks(0.0, 0.010), vec![]);
1945        assert_eq!(r.nacks(0.02, 0.010), vec![(1, 1)]);
1946        r.insert(1, 1);
1947        assert_eq!(r.nacks(0.06, 0.010), vec![]);
1948        let rtt = r.rtt().expect("a measure");
1949        assert!((rtt - 0.04).abs() < 1e-9, "{rtt}");
1950        // The next gap is asked again after 1.5 x 40 ms.
1951        r.insert(4, 4);
1952        take(&mut r);
1953        assert_eq!(r.nacks(0.09, 0.010), vec![]);
1954        assert_eq!(r.nacks(0.10, 0.010), vec![(3, 1)]);
1955        assert_eq!(r.nacks(0.159, 0.010), vec![]);
1956        assert_eq!(r.nacks(0.161, 0.010), vec![(3, 1)]);
1957    }
1958
1959    #[test]
1960    fn a_small_gap_behind_a_tcp_resend_gets_its_full_time_at_the_expected_number() {
1961        let mut r = Reorder::new();
1962        r.set_small_gaps(64, 1.0);
1963        r.start(0);
1964        // The `resume` resend 0..100 is on the way on TCP, and the live
1965        // samples on UDP have a small gap at 150.
1966        r.assume_requested(0, 100, 0.0);
1967        for n in (100..150).chain(151..200) {
1968            r.insert(n, n);
1969        }
1970        assert_eq!(r.nacks(0.0, 0.010), vec![]);
1971        assert_eq!(r.nacks(0.02, 0.010), vec![(150, 1)], "asked for at once");
1972        // The TCP resend ends after 1.5 s on a slow link. Its data holds
1973        // off the give-up of the TCP part.
1974        for t in [0.4, 0.8, 1.2] {
1975            r.progress(t);
1976            assert_eq!(r.poll(t, 0.010, 0.5), None);
1977        }
1978        for n in 0..100 {
1979            r.progress(1.5);
1980            r.insert(n, n);
1981        }
1982        assert_eq!(take(&mut r).len(), 150);
1983        assert_eq!(r.poll(1.5, 0.010, 0.5), None, "the gap just reached E");
1984        assert_eq!(r.poll(2.4, 0.010, 0.5), None);
1985        assert_eq!(
1986            r.poll(2.5, 0.010, 0.5),
1987            Some(Action::GaveUp {
1988                from: 150,
1989                count: 1
1990            })
1991        );
1992    }
1993
1994    #[test]
1995    fn on_a_link_with_a_long_queue_a_small_gap_waits_4_round_trips() {
1996        let mut r = Reorder::new();
1997        r.set_small_gaps(64, 1.0);
1998        r.start(0);
1999        r.insert(0, 0);
2000        r.insert(2, 2);
2001        take(&mut r);
2002        assert_eq!(r.nacks(0.0, 0.010), vec![]);
2003        assert_eq!(r.nacks(0.02, 0.010), vec![(1, 1)]);
2004        // The answer comes after 0.5 s.
2005        r.insert(1, 1);
2006        let _ = r.nacks(0.52, 0.010);
2007        assert!((r.rtt().unwrap() - 0.5).abs() < 1e-9);
2008        take(&mut r);
2009        r.insert(4, 4);
2010        assert_eq!(r.poll(1.0, 0.010, 0.5), None);
2011        assert_eq!(r.poll(2.9, 0.010, 0.5), None, "4 x 0.5 s, not 1 s");
2012        assert_eq!(
2013            r.poll(3.0, 0.010, 0.5),
2014            Some(Action::GaveUp { from: 3, count: 1 })
2015        );
2016    }
2017
2018    #[test]
2019    fn a_gap_in_the_resume_resend_is_not_a_small_gap() {
2020        let mut r = Reorder::new();
2021        r.set_small_gaps(64, 1.0);
2022        r.start(0);
2023        r.assume_requested(0, 50, 0.0);
2024        r.insert(10, 10);
2025        assert_eq!(r.nacks(0.1, 0.010), vec![]);
2026        assert_eq!(r.poll(0.1, 0.010, 0.5), None);
2027    }
2028
2029    #[test]
2030    fn a_small_gap_is_not_given_up_during_a_cut() {
2031        let mut r = Reorder::new();
2032        r.set_small_gaps(64, 1.0);
2033        r.start(0);
2034        r.udp_heard(0.0);
2035        r.insert(0, 0);
2036        r.insert(2, 2);
2037        take(&mut r);
2038        assert_eq!(r.poll(0.0, 0.010, 0.5), None);
2039        // A cut stops all datagrams. The gap stays open for `resume/1`.
2040        for t in [0.5, 1.1, 2.0] {
2041            assert_eq!(r.poll(t, 0.010, 0.5), None);
2042        }
2043        assert_eq!(r.expected(), Some(1));
2044        assert_eq!(r.lost(), 0);
2045        // After the cut, the gap gets a full wait to recover on UDP.
2046        r.udp_heard(3.0);
2047        r.insert(10, 10);
2048        assert_eq!(r.poll(3.0, 0.010, 0.5), None);
2049        r.udp_heard(3.9);
2050        assert_eq!(r.poll(3.9, 0.010, 0.5), None);
2051        r.udp_heard(4.0);
2052        assert_eq!(
2053            r.poll(4.0, 0.010, 0.5),
2054            Some(Action::GaveUp { from: 1, count: 1 })
2055        );
2056    }
2057
2058    #[test]
2059    fn a_quiet_live_outlet_still_gives_up_a_small_gap_on_idle() {
2060        let mut r = Reorder::new();
2061        r.set_small_gaps(64, 1.0);
2062        r.start(0);
2063        r.udp_heard(0.0);
2064        r.insert(0, 0);
2065        r.insert(2, 2);
2066        take(&mut r);
2067        assert_eq!(r.poll(0.0, 0.010, 0.5), None);
2068        // Tail idle at 250 ms, then periodic idle at 1.25 s.
2069        r.udp_heard(0.25);
2070        assert_eq!(r.poll(1.0, 0.010, 0.5), None);
2071        r.udp_heard(1.25);
2072        assert_eq!(
2073            r.poll(1.25, 0.010, 0.5),
2074            Some(Action::GaveUp { from: 1, count: 1 })
2075        );
2076    }
2077
2078    #[test]
2079    fn push_slices_matches_push_for_copies_and_large_samples() {
2080        for copies in [0u8, 2] {
2081            let mut a = Packer::new(77);
2082            let mut b = Packer::new(77);
2083            a.set_copies(copies);
2084            b.set_copies(copies);
2085            let block = vec![sample(0, 41), sample(1, 41), sample(2, 2000), sample(3, 41)];
2086            let slices: Vec<&[u8]> = block.iter().map(Vec::as_slice).collect();
2087            let mut out_a = Vec::new();
2088            a.push(0, &block, &mut out_a);
2089            let out_b = std::cell::RefCell::new(Vec::new());
2090            let mut gram = Vec::new();
2091            b.push_slices(
2092                0,
2093                &slices,
2094                &mut gram,
2095                |d| out_b.borrow_mut().push(Packet::Datagram(d.to_vec())),
2096                |n| out_b.borrow_mut().push(Packet::Tcp(n)),
2097            );
2098            assert_eq!(out_a, *out_b.borrow(), "copies={copies}");
2099            assert_eq!(a.serial(), b.serial());
2100        }
2101    }
2102
2103    #[test]
2104    fn insert_or_emit_fast_path_matches_insert_and_drain() {
2105        let mut r = Reorder::new();
2106        r.start(0);
2107        let mut out = Vec::new();
2108        assert!(r.insert_or_emit(0, 10, &mut out));
2109        assert!(r.insert_or_emit(1, 11, &mut out));
2110        assert!(!r.has_gaps());
2111        assert_eq!(out, vec![10, 11]);
2112        // Out of order goes into the buffer until the missing number arrives.
2113        assert!(r.insert_or_emit(3, 13, &mut out));
2114        assert!(r.has_gaps());
2115        assert_eq!(out, vec![10, 11]);
2116        assert!(r.insert_or_emit(2, 12, &mut out));
2117        r.drain(&mut out);
2118        assert!(!r.has_gaps());
2119        assert_eq!(out, vec![10, 11, 12, 13]);
2120    }
2121
2122    /// A small random number source, so the simulation repeats.
2123    struct Rng(u64);
2124
2125    impl Rng {
2126        fn unit(&mut self) -> f64 {
2127            self.0 ^= self.0 << 13;
2128            self.0 ^= self.0 >> 7;
2129            self.0 ^= self.0 << 17;
2130            (self.0 >> 11) as f64 / (1u64 << 53) as f64
2131        }
2132    }
2133
2134    /// The result of one simulated run.
2135    #[derive(Debug)]
2136    struct Sim {
2137        lost: u64,
2138        p99: f64,
2139        bytes: usize,
2140    }
2141
2142    /// Simulate 10 s of a 512 Hz x 8 channel stream in chunks of `chunk`, with `loss`
2143    /// in each direction and 20 ms delay. With `repair`, the inlet asks for
2144    /// the small gaps on UDP and the outlet follows the measured loss. With
2145    /// no `repair`, the outlet sends 2 copies and a request on TCP gets no
2146    /// answer, as with TCP at heavy loss.
2147    fn simulate(loss: f64, repair: bool, seed: u64, chunk: u64) -> Sim {
2148        const DELAY: f64 = 0.020;
2149        const RATE: f64 = 512.0;
2150        const LEN: usize = 41;
2151        let total = (RATE * 10.0) as u64;
2152        let mut rng = Rng(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1);
2153        let mut packer = Packer::new(1);
2154        let mut control = CopyControl::new();
2155        if !repair {
2156            packer.set_copies(2);
2157        }
2158        let mut reorder: Reorder<u64> = Reorder::new();
2159        if repair {
2160            reorder.set_small_gaps(64, 1.0);
2161        }
2162        let mut meter = LossMeter::new();
2163        let mut forward: Vec<(f64, Vec<u8>)> = Vec::new();
2164        let mut back: Vec<(f64, Vec<u8>)> = Vec::new();
2165        let mut resent_at = std::collections::HashMap::new();
2166        let mut delays = Vec::new();
2167        let (mut next, mut last_data, mut repeated, mut bytes) = (0u64, 0.0, true, 0usize);
2168        let mut idles = 0usize;
2169        let mut last_feedback = 0.0;
2170        let mut started = false;
2171        let send = |d: Vec<u8>, t: f64, rng: &mut Rng, to: &mut Vec<(f64, Vec<u8>)>| {
2172            if rng.unit() >= loss {
2173                to.push((t + DELAY, d));
2174            }
2175        };
2176        // The mean time between two datagrams at the inlet, as in the inlet.
2177        let (mut period, mut last_arrival) = (0.0f64, 0.0f64);
2178        let mut pushed = vec![0.0f64; total as usize];
2179        for tick in 0..13_000u64 {
2180            let t = tick as f64 * 0.001;
2181            // The outlet: new samples, the repeat, and the idle datagrams.
2182            while next < total && (next + chunk.min(total - next)) as f64 / RATE <= t {
2183                let n = chunk.min(total - next);
2184                let block: Vec<Vec<u8>> = (0..n).map(|_| vec![0u8; LEN]).collect();
2185                let mut out = Vec::new();
2186                packer.push(next, &block, &mut out);
2187                for p in out {
2188                    if let Packet::Datagram(d) = p {
2189                        bytes += d.len();
2190                        send(d, t, &mut rng, &mut forward);
2191                    }
2192                }
2193                for k in next..next + n {
2194                    pushed[k as usize] = t;
2195                }
2196                next += n;
2197                last_data = t;
2198                repeated = false;
2199                idles = 0;
2200            }
2201            if !repeated && t - last_data >= 0.005 {
2202                let d = packer.repeat().unwrap_or_else(|| idle(1, next).to_vec());
2203                send(d, t, &mut rng, &mut forward);
2204                repeated = true;
2205            }
2206            let tail = [0.025, 0.100, 0.250];
2207            if idles < tail.len() && t - last_data >= tail[idles] {
2208                send(idle(1, next).to_vec(), t, &mut rng, &mut forward);
2209                idles += 1;
2210            }
2211            // The outlet: the feedback of the inlet.
2212            let (due, rest): (Vec<_>, Vec<_>) = back.drain(..).partition(|(at, _)| *at <= t);
2213            back = rest;
2214            for (_, d) in due {
2215                let Ok(Datagram::Feedback { loss: l, gaps, .. }) = parse(&d) else {
2216                    panic!("a feedback datagram");
2217                };
2218                packer.set_copies(control.report(l, t, packer.serial()));
2219                let mut budget = 256;
2220                for (from, count) in gaps.iter() {
2221                    let numbers: Vec<u64> = (from..from + count as u64)
2222                        .filter(|n| *n < next)
2223                        .filter(|n| resent_at.get(n).map_or(true, |&a: &f64| t - a >= 0.010))
2224                        .take(budget)
2225                        .collect();
2226                    budget -= numbers.len();
2227                    for &n in &numbers {
2228                        resent_at.insert(n, t);
2229                        let mut grams = Vec::new();
2230                        packer.resend(n, &[vec![0u8; LEN]], &mut grams);
2231                        for g in grams {
2232                            let times = if control.copies() >= 3 { 2 } else { 1 };
2233                            for _ in 0..times {
2234                                send(g.clone(), t, &mut rng, &mut forward);
2235                            }
2236                        }
2237                    }
2238                }
2239            }
2240            // The inlet.
2241            let (due, rest): (Vec<_>, Vec<_>) = forward.drain(..).partition(|(at, _)| *at <= t);
2242            forward = rest;
2243            for (_, d) in due {
2244                let gap = t - last_arrival;
2245                period = if period == 0.0 {
2246                    gap
2247                } else {
2248                    0.9 * period + 0.1 * gap
2249                };
2250                last_arrival = t;
2251                match parse(&d) {
2252                    Ok(Datagram::Data {
2253                        first,
2254                        count,
2255                        serial,
2256                        ..
2257                    }) => {
2258                        if !started {
2259                            reorder.start(first);
2260                            started = true;
2261                        }
2262                        meter.record(serial, t);
2263                        for k in 0..count as u64 {
2264                            reorder.insert(first + k, first + k);
2265                        }
2266                    }
2267                    Ok(Datagram::Idle { next, .. }) => reorder.idle(next),
2268                    other => panic!("{other:?}"),
2269                }
2270            }
2271            let wait = MIN_REPEAT.max(2.0 * period);
2272            let mut out = Vec::new();
2273            reorder.drain(&mut out);
2274            let _ = reorder.poll(t, wait, 0.5);
2275            reorder.drain(&mut out);
2276            for n in out {
2277                if n as f64 / RATE >= 1.0 {
2278                    delays.push(t - pushed[n as usize]);
2279                    if std::env::var_os("SIMDBG").is_some() && t - pushed[n as usize] > 0.035 {
2280                        eprintln!(
2281                            "late {n} pushed {:.3} delay {:.3} copies {}",
2282                            pushed[n as usize],
2283                            t - pushed[n as usize],
2284                            packer.copies()
2285                        );
2286                    }
2287                }
2288            }
2289            if repair {
2290                let gaps = reorder.nacks(t, wait);
2291                if !gaps.is_empty() || t - last_feedback >= 0.1 {
2292                    send(
2293                        feedback(1, meter.loss_ppm(t), &gaps),
2294                        t,
2295                        &mut rng,
2296                        &mut back,
2297                    );
2298                    last_feedback = t;
2299                }
2300            }
2301        }
2302        let delivered = delays.len() as u64 + RATE as u64;
2303        delays.sort_by(|a, b| a.partial_cmp(b).unwrap());
2304        Sim {
2305            lost: total.saturating_sub(delivered),
2306            p99: delays[delays.len() * 99 / 100],
2307            bytes,
2308        }
2309    }
2310
2311    #[test]
2312    fn at_30_percent_loss_the_repair_on_udp_loses_no_sample() {
2313        for seed in 1..=4 {
2314            let s = simulate(0.30, true, seed, 1);
2315            assert_eq!(s.lost, 0, "seed {seed}: {s:?}");
2316        }
2317    }
2318
2319    #[test]
2320    fn at_50_percent_loss_the_repair_on_udp_loses_at_most_0_1_percent() {
2321        for seed in 1..=4 {
2322            let s = simulate(0.50, true, seed, 1);
2323            assert!(s.lost <= 5, "seed {seed}: {s:?}");
2324        }
2325    }
2326
2327    #[test]
2328    fn without_the_repair_on_udp_30_percent_loss_loses_samples() {
2329        let s = simulate(0.30, false, 1, 1);
2330        assert!(s.lost > 0, "{s:?}");
2331    }
2332
2333    #[test]
2334    fn at_1_percent_loss_the_p99_stays_near_the_delay() {
2335        for seed in 1..=4 {
2336            let s = simulate(0.01, true, seed, 1);
2337            assert_eq!(s.lost, 0, "seed {seed}: {s:?}");
2338            assert!(s.p99 < 0.035, "seed {seed}: {s:?}");
2339        }
2340    }
2341
2342    #[test]
2343    fn at_1_percent_loss_with_chunks_of_16_the_p99_stays_near_the_delay() {
2344        // Chunks of 16 give few datagrams, so a window of 1 s often shows no
2345        // loss. The copies must not go away on such thin evidence.
2346        for seed in 1..=8 {
2347            let s = simulate(0.01, true, seed, 16);
2348            assert_eq!(s.lost, 0, "seed {seed}: {s:?}");
2349            assert!(s.p99 < 0.035, "seed {seed}: {s:?}");
2350        }
2351    }
2352
2353    #[test]
2354    fn a_clean_link_sends_no_copy() {
2355        let clean = simulate(0.0, true, 1, 1);
2356        let fixed = simulate(0.0, false, 1, 1);
2357        assert_eq!(clean.lost, 0);
2358        assert_eq!(clean.bytes, 5120 * (DATA_HEADER + 41), "{clean:?}");
2359        assert!(fixed.bytes > 2 * clean.bytes, "{fixed:?}");
2360    }
2361}