Skip to main content

vector_calls/
rate.rs

1//! Bitrate control for the encoder, fed by QUIC's own loss accounting: every
2//! datagram rides in a packet the peer acknowledges, so the sender learns what
3//! went missing without a report channel. A lossy link steps the ladder down at
4//! once; a clean one climbs back a rung at a time.
5//!
6//! Loss is not the whole story. A relay carries QUIC inside TCP, where a full pipe
7//! shows as delay and never as loss, so the round trip's growth over the path's
8//! floor counts as trouble too.
9
10/// Bitrates the encoder may use, in kbit/s. Opus picks the audio bandwidth to
11/// match: narrowband at the bottom, fullband from the middle up.
12pub const LADDER: [u32; 8] = [12, 16, 20, 24, 32, 40, 48, 64];
13pub const START_KBPS: u32 = 32;
14/// Loss in one second that costs a rung.
15const DOWN_AT_PCT: f32 = 4.0;
16/// Loss a second must stay under to count towards climbing.
17const CLEAN_PCT: f32 = 1.0;
18/// Clean seconds in a row before the next rung up.
19const CLIMB_AFTER_SECS: u32 = 8;
20/// Seconds a rung down is held before loss may take another. Loss is reported
21/// about a round trip late, so a step needs time to show in the numbers.
22const HOLD_SECS: u32 = 3;
23/// The FEC budget follows the loss actually seen, within these bounds.
24const FEC_MIN_PCT: u32 = 5;
25const FEC_MAX_PCT: u32 = 30;
26/// Round trip over the path's floor that reads as a standing queue: at least this
27/// much and at least the floor again, so an intercontinental path's ordinary swing
28/// is not mistaken for one.
29const QUEUE_MIN_MS: u32 = 300;
30/// A queue this deep, or this much loss in a second, is past a rung at a time.
31const SEVERE_QUEUE_MS: u32 = 1500;
32const SEVERE_LOSS_PCT: f32 = 15.0;
33/// Where a severe second puts the voice at once: still wideband.
34const SEVERE_KBPS: u32 = 32;
35
36/// Seconds per bucket of a round-trip floor, and how many buckets it keeps.
37const FLOOR_BUCKET_SECS: u32 = 10;
38const FLOOR_BUCKETS: usize = 30;
39
40/// The lowest round trip a path has shown over the last few minutes: what it costs
41/// with no queue of ours in it. Kept per path kind, so falling back to a relay
42/// neither borrows the direct path's floor nor relearns its own from a queue we filled.
43#[derive(Default)]
44pub struct RttFloor {
45    paths: [FloorWindow; 2],
46}
47
48#[derive(Clone, Copy)]
49struct FloorWindow {
50    buckets: [u32; FLOOR_BUCKETS],
51    at: usize,
52    secs: u32,
53}
54
55impl Default for FloorWindow {
56    fn default() -> Self {
57        Self { buckets: [u32::MAX; FLOOR_BUCKETS], at: 0, secs: 0 }
58    }
59}
60
61impl RttFloor {
62    /// Once a second, with the selected path's round trip (0 when unknown). Returns
63    /// that path's floor once it has one.
64    pub fn observe(&mut self, rtt_ms: u32, relay: bool) -> Option<u32> {
65        let w = &mut self.paths[relay as usize];
66        if rtt_ms > 0 {
67            if w.secs == FLOOR_BUCKET_SECS {
68                w.at = (w.at + 1) % FLOOR_BUCKETS;
69                w.buckets[w.at] = u32::MAX;
70                w.secs = 0;
71            }
72            w.buckets[w.at] = w.buckets[w.at].min(rtt_ms);
73            w.secs += 1;
74        }
75        let floor = w.buckets.iter().copied().min().unwrap_or(u32::MAX);
76        (floor != u32::MAX).then_some(floor)
77    }
78}
79
80/// A round trip that has grown past what the path's ordinary swing explains.
81fn queued(rtt_ms: u32, floor: Option<u32>) -> bool {
82    floor.is_some_and(|f| rtt_ms > f.saturating_add(QUEUE_MIN_MS.max(f)))
83}
84
85fn severe(rtt_ms: u32, floor: Option<u32>, loss_pct: f32) -> bool {
86    loss_pct >= SEVERE_LOSS_PCT || floor.is_some_and(|f| rtt_ms > f.saturating_add(SEVERE_QUEUE_MS))
87}
88
89pub struct RateControl {
90    rung: usize,
91    clean_secs: u32,
92    hold: u32,
93    last_sent: u64,
94    last_lost: u64,
95    /// Loss smoothed over a few seconds, for the FEC budget.
96    loss_avg: f32,
97    floor: RttFloor,
98}
99
100/// What the encoder should be set to after an observation.
101#[derive(Debug, Clone, Copy, PartialEq, Eq)]
102pub struct Setting {
103    pub kbps: u32,
104    pub fec_pct: u32,
105}
106
107impl RateControl {
108    pub fn new() -> Self {
109        let rung = LADDER.iter().position(|&k| k == START_KBPS).unwrap_or(0);
110        Self { rung, clean_secs: 0, hold: 0, last_sent: 0, last_lost: 0, loss_avg: 0.0, floor: RttFloor::default() }
111    }
112
113    /// Sets the baseline so the first observation covers only the next second.
114    pub fn prime(&mut self, sent_packets: u64, lost_packets: u64) {
115        self.last_sent = sent_packets;
116        self.last_lost = lost_packets;
117    }
118
119    pub fn kbps(&self) -> u32 {
120        LADDER[self.rung]
121    }
122
123    /// Loss seen in the last observed second, in percent.
124    pub fn loss_pct(&self) -> f32 {
125        self.loss_avg
126    }
127
128    /// Once a second, with the path's cumulative packet counts and the selected
129    /// path's round trip (0 when unknown). Returns a new setting when the encoder
130    /// should change.
131    pub fn observe(&mut self, sent_packets: u64, lost_packets: u64, rtt_ms: u32, relay: bool) -> Option<Setting> {
132        let sent = sent_packets.saturating_sub(self.last_sent);
133        let lost = lost_packets.saturating_sub(self.last_lost);
134        self.last_sent = sent_packets;
135        self.last_lost = lost_packets;
136        let floor = self.floor.observe(rtt_ms, relay);
137        // Too few packets to judge: a call sends fifty a second.
138        if sent < 10 {
139            return None;
140        }
141        let loss = 100.0 * lost as f32 / sent as f32;
142        self.loss_avg += (loss - self.loss_avg) * 0.3;
143        let before = self.setting();
144        if self.hold > 0 {
145            self.hold -= 1;
146        }
147        let severe = severe(rtt_ms, floor, loss);
148        if severe && self.kbps() > SEVERE_KBPS {
149            self.rung = LADDER.iter().position(|&k| k == SEVERE_KBPS).unwrap_or(0);
150            self.clean_secs = 0;
151            self.hold = HOLD_SECS;
152        } else if severe || loss >= DOWN_AT_PCT || queued(rtt_ms, floor) {
153            self.clean_secs = 0;
154            if self.hold == 0 && self.rung > 0 {
155                self.rung -= 1;
156                self.hold = HOLD_SECS;
157            }
158        } else if loss < CLEAN_PCT {
159            self.clean_secs += 1;
160            if self.clean_secs >= CLIMB_AFTER_SECS && self.rung + 1 < LADDER.len() {
161                self.rung += 1;
162                self.clean_secs = 0;
163            }
164        } else {
165            self.clean_secs = 0;
166        }
167        let after = self.setting();
168        (after != before).then_some(after)
169    }
170
171    /// The encoder setting this ladder stands at now.
172    pub fn setting(&self) -> Setting {
173        let fec = (self.loss_avg.round() as u32).clamp(FEC_MIN_PCT, FEC_MAX_PCT);
174        Setting { kbps: self.kbps(), fec_pct: fec }
175    }
176}
177
178/// One link's cumulative counts and path, once a second.
179#[derive(Debug, Clone, Copy)]
180pub struct LinkSample {
181    pub id: u64,
182    pub sent_packets: u64,
183    pub lost_packets: u64,
184    pub rtt_ms: u32,
185    pub relay: bool,
186}
187
188/// A voice Channel encodes each frame once for every peer, so the encoder runs at its
189/// weakest link: each link keeps its own ladder, the lowest rung and the largest FEC
190/// budget win, and the whole stays under a ceiling a mesh's upload can afford.
191pub struct MeshRate {
192    links: Vec<(u64, RateControl)>,
193    ceiling_kbps: u32,
194    current: Option<Setting>,
195}
196
197impl MeshRate {
198    pub fn new(ceiling_kbps: u32) -> Self {
199        Self { links: Vec::new(), ceiling_kbps, current: None }
200    }
201
202    /// Once a second, with every live link. Returns a new setting when the encoder
203    /// should change; a link seen for the first time only sets its baseline.
204    pub fn observe(&mut self, samples: &[LinkSample]) -> Option<Setting> {
205        self.links.retain(|(id, _)| samples.iter().any(|s| s.id == *id));
206        for s in samples {
207            match self.links.iter_mut().find(|(id, _)| *id == s.id) {
208                Some((_, rc)) => {
209                    rc.observe(s.sent_packets, s.lost_packets, s.rtt_ms, s.relay);
210                }
211                None => {
212                    let mut rc = RateControl::new();
213                    rc.prime(s.sent_packets, s.lost_packets);
214                    self.links.push((s.id, rc));
215                }
216            }
217        }
218        let worst = self
219            .links
220            .iter()
221            .map(|(_, rc)| rc.setting())
222            .reduce(|a, b| Setting { kbps: a.kbps.min(b.kbps), fec_pct: a.fec_pct.max(b.fec_pct) })?;
223        let next = Setting { kbps: worst.kbps.min(self.ceiling_kbps), ..worst };
224        (self.current != Some(next)).then(|| {
225            self.current = Some(next);
226            next
227        })
228    }
229
230    /// The worst link's recent loss, in percent.
231    pub fn loss_pct(&self) -> f32 {
232        self.links.iter().map(|(_, rc)| rc.loss_pct()).fold(0.0, f32::max)
233    }
234}
235
236#[cfg(test)]
237mod tests {
238    use super::*;
239
240    #[test]
241    fn loss_steps_down_at_once_and_a_clean_link_climbs_slowly() {
242        let mut rc = RateControl::new();
243        assert_eq!(rc.kbps(), 32);
244        // 10% loss for one second: one rung, then held.
245        assert_eq!(rc.observe(50, 5, 0, false).map(|s| s.kbps), Some(24));
246        assert_eq!(rc.observe(100, 10, 0, false), None);
247        assert_eq!(rc.observe(150, 15, 0, false), None);
248        assert_eq!(rc.observe(200, 20, 0, false).map(|s| s.kbps), Some(20));
249        // Clean seconds climb one rung every CLIMB_AFTER_SECS.
250        let mut sent = 200;
251        let mut changes = vec![];
252        for _ in 0..(CLIMB_AFTER_SECS * 4) {
253            sent += 50;
254            if let Some(s) = rc.observe(sent, 20, 0, false) {
255                changes.push(s.kbps);
256            }
257        }
258        assert_eq!(changes, vec![24, 32, 40, 48]);
259    }
260
261    #[test]
262    fn the_fec_budget_follows_the_loss_and_a_quiet_second_is_ignored() {
263        let mut rc = RateControl::new();
264        assert_eq!(rc.observe(5, 0, 0, false), None);
265        assert_eq!(rc.observe(55, 10, 0, false).map(|s| s.fec_pct), Some(6));
266        let mut sent = 55;
267        let mut last = None;
268        for _ in 0..6 {
269            sent += 50;
270            if let Some(s) = rc.observe(sent, 10 + (sent - 55) / 5, 0, false) {
271                last = Some(s);
272            }
273        }
274        assert_eq!(last.map(|s| s.fec_pct), Some(18));
275    }
276
277    /// Seconds of a clean call at `rtt`, from `sent` packets on; returns the packet count.
278    fn clean_secs(rc: &mut RateControl, mut sent: u64, secs: u32, rtt: u32, relay: bool) -> u64 {
279        for _ in 0..secs {
280            sent += 50;
281            rc.observe(sent, 0, rtt, relay);
282        }
283        sent
284    }
285
286    #[test]
287    fn a_queue_on_a_relay_steps_the_voice_down_without_any_loss() {
288        let mut rc = RateControl::new();
289        let sent = clean_secs(&mut rc, 0, 3, 400, true);
290        // TCP under the relay turns a full pipe into delay: no packet is ever lost.
291        assert_eq!(rc.observe(sent + 50, 0, 900, true).map(|s| s.kbps), Some(24));
292    }
293
294    #[test]
295    fn an_intercontinental_swing_is_not_a_queue() {
296        let mut rc = RateControl::new();
297        let mut sent = 0;
298        let mut kbps = vec![];
299        for i in 0..(CLIMB_AFTER_SECS * 3) {
300            sent += 50;
301            let rtt = if i % 2 == 0 { 300 } else { 550 };
302            if let Some(s) = rc.observe(sent, 0, rtt, true) {
303                kbps.push(s.kbps);
304            }
305        }
306        assert_eq!(kbps, vec![40, 48, 64], "300 to 550 ms with no loss is a clean call");
307        // A slow path's floor widens its own tolerance: double the floor before it's a queue.
308        assert!(!queued(1400, Some(800)));
309        assert!(queued(1700, Some(800)));
310    }
311
312    #[test]
313    fn a_severe_queue_drops_the_voice_to_wideband_at_once_and_keeps_stepping() {
314        let mut rc = RateControl::new();
315        let sent = clean_secs(&mut rc, 0, CLIMB_AFTER_SECS * 3, 400, true);
316        assert_eq!(rc.kbps(), 64);
317        assert_eq!(rc.observe(sent + 50, 0, 6000, true).map(|s| s.kbps), Some(SEVERE_KBPS));
318        let mut sent = sent + 50;
319        for _ in 0..HOLD_SECS {
320            sent += 50;
321            rc.observe(sent, 0, 6000, true);
322        }
323        assert_eq!(rc.kbps(), 24, "a queue that stays keeps costing rungs");
324        // Severe loss is the same emergency without the delay.
325        let mut lossy = RateControl::new();
326        let sent = clean_secs(&mut lossy, 0, CLIMB_AFTER_SECS * 3, 0, false);
327        assert_eq!(lossy.observe(sent + 50, 10, 0, false).map(|s| s.kbps), Some(SEVERE_KBPS));
328    }
329
330    #[test]
331    fn the_floor_is_kept_per_path_and_forgets_after_its_window() {
332        let mut f = RttFloor::default();
333        assert_eq!(f.observe(0, false), None, "an unknown round trip teaches nothing");
334        assert_eq!(f.observe(50, false), Some(50));
335        assert_eq!(f.observe(400, true), Some(400), "a relay never borrows the direct path's floor");
336        assert_eq!(f.observe(6000, true), Some(400), "nor relearns its own from a queue");
337        assert_eq!(f.observe(80, false), Some(50));
338        for _ in 0..(FLOOR_BUCKET_SECS * FLOOR_BUCKETS as u32) {
339            f.observe(700, true);
340        }
341        assert_eq!(f.observe(700, true), Some(700), "a path that really got slower is relearned");
342    }
343}
344
345/// One step of a video ladder. `height` caps the picture: a camera is asked for
346/// `width` by `height`, a screen is scaled to at most `height` tall (0 keeps it native).
347#[derive(Debug, Clone, Copy, PartialEq, Eq)]
348pub struct Rung {
349    pub kbps: u32,
350    pub width: u32,
351    pub height: u32,
352    pub fps: u32,
353}
354
355pub static CAMERA_LADDER: [Rung; 7] = [
356    Rung { kbps: 150, width: 320, height: 180, fps: 15 },
357    Rung { kbps: 300, width: 480, height: 270, fps: 15 },
358    Rung { kbps: 500, width: 640, height: 360, fps: 24 },
359    Rung { kbps: 800, width: 640, height: 360, fps: 30 },
360    Rung { kbps: 1200, width: 960, height: 540, fps: 30 },
361    Rung { kbps: 1800, width: 1280, height: 720, fps: 30 },
362    Rung { kbps: 2500, width: 1280, height: 720, fps: 30 },
363];
364/// The top three are for games: 60 frames a second, and enough bits to keep them crisp.
365pub static SCREEN_LADDER: [Rung; 9] = [
366    Rung { kbps: 300, width: 0, height: 720, fps: 5 },
367    Rung { kbps: 600, width: 0, height: 1080, fps: 8 },
368    Rung { kbps: 1000, width: 0, height: 1080, fps: 10 },
369    Rung { kbps: 1500, width: 0, height: 1440, fps: 15 },
370    Rung { kbps: 2500, width: 0, height: 0, fps: 30 },
371    Rung { kbps: 4000, width: 0, height: 0, fps: 30 },
372    Rung { kbps: 6000, width: 0, height: 1080, fps: 60 },
373    Rung { kbps: 10000, width: 0, height: 0, fps: 60 },
374    Rung { kbps: 16000, width: 0, height: 0, fps: 60 },
375];
376/// Where a fresh camera or screen starts, and the most a relayed path may carry:
377/// the relays are not ours yet, and a video call must not be what fills them.
378pub const CAMERA_START: usize = 4;
379pub const CAMERA_RELAY_CAP: usize = 4;
380pub const SCREEN_START: usize = 3;
381pub const SCREEN_RELAY_CAP: usize = 3;
382
383/// Video steps down sooner than audio, since both share one congestion window and
384/// the voice must never be what gives.
385const VIDEO_DOWN_AT_PCT: f32 = 2.0;
386/// Round-trip growth over the call's floor that reads as a filling buffer.
387const VIDEO_RTT_BLOAT_MS: u32 = 50;
388/// Clean seconds before video takes the next rung: sooner than the voice, since a
389/// rung of video is worth more and costs less to give back.
390const VIDEO_CLIMB_AFTER_SECS: u32 = 5;
391
392/// The round trip the video's in-flight budget is sized to: the path's, but never
393/// past twice its floor. Beyond that the round trip is our own queue, and a budget
394/// that grew with it would keep it full.
395pub fn budget_rtt(rtt_ms: u32, floor: Option<u32>) -> u32 {
396    floor.map_or(rtt_ms, |f| rtt_ms.min(f.saturating_mul(2)))
397}
398
399/// What the video controller sees once a second.
400#[derive(Debug, Clone, Copy, Default)]
401pub struct VideoObservation {
402    pub sent_packets: u64,
403    pub lost_packets: u64,
404    pub rtt_ms: u32,
405    /// The selected path's [`RttFloor`], once it has one.
406    pub floor_ms: Option<u32>,
407    /// Audio datagrams the connection refused, cumulative: any growth is a step down.
408    pub audio_send_dropped: u64,
409    /// Frames still on the wire at the cap, or a frame reset, in the last second.
410    pub backlog: bool,
411}
412
413pub struct VideoRate {
414    ladder: &'static [Rung],
415    camera: bool,
416    rung: usize,
417    cap: usize,
418    clean_secs: u32,
419    hold: u32,
420    last_sent: u64,
421    last_lost: u64,
422    last_audio_dropped: u64,
423    primed: bool,
424    /// A rung the user chose; the ladder only leaves it to protect the voice.
425    pin: Option<usize>,
426    /// A frame rate the user chose, over whatever the rung says.
427    fps: Option<u32>,
428}
429
430impl VideoRate {
431    pub fn camera(cap: usize) -> Self {
432        Self::new(&CAMERA_LADDER, true, CAMERA_START, cap)
433    }
434
435    pub fn screen(cap: usize) -> Self {
436        Self::new(&SCREEN_LADDER, false, SCREEN_START, cap)
437    }
438
439    pub fn new(ladder: &'static [Rung], camera: bool, start: usize, cap: usize) -> Self {
440        let cap = cap.min(ladder.len() - 1);
441        Self {
442            ladder,
443            camera,
444            rung: start.min(cap),
445            cap,
446            clean_secs: 0,
447            hold: 0,
448            last_sent: 0,
449            last_lost: 0,
450            last_audio_dropped: 0,
451            primed: false,
452            pin: None,
453            fps: None,
454        }
455    }
456
457    pub fn rung(&self) -> Rung {
458        let mut r = self.ladder[self.rung];
459        if let Some(fps) = self.fps {
460            r.fps = fps;
461        }
462        r
463    }
464
465    pub fn rungs(&self) -> usize {
466        self.ladder.len()
467    }
468
469    /// Hold a rung, or let the ladder run again. A held rung may sit above the
470    /// path's cap: the cap is a default for the ladder, the pin is the user's word.
471    /// Returns the rung when it moved.
472    pub fn set_pin(&mut self, pin: Option<usize>) -> Option<Rung> {
473        let before = self.rung;
474        self.pin = pin.map(|p| p.min(self.ladder.len() - 1));
475        if let Some(p) = self.pin {
476            self.rung = p;
477        } else if self.rung > self.cap {
478            self.rung = self.cap;
479        }
480        self.clean_secs = 0;
481        (self.rung != before || pin.is_some()).then(|| self.rung())
482    }
483
484    pub fn set_fps(&mut self, fps: Option<u32>) -> Rung {
485        self.fps = fps;
486        self.rung()
487    }
488
489    pub fn is_camera(&self) -> bool {
490        self.camera
491    }
492
493    /// A new ceiling (the path changed, or the peer said how much it can take).
494    /// Returns the rung when the ceiling pushed it down.
495    pub fn set_cap(&mut self, cap: usize) -> Option<Rung> {
496        self.cap = cap.min(self.ladder.len() - 1);
497        if self.pin.is_none() && self.rung > self.cap {
498            self.rung = self.cap;
499            return Some(self.rung());
500        }
501        None
502    }
503
504    /// Once a second. Returns the rung to switch to when it changed.
505    pub fn observe(&mut self, obs: VideoObservation) -> Option<Rung> {
506        let sent = obs.sent_packets.saturating_sub(self.last_sent);
507        let lost = obs.lost_packets.saturating_sub(self.last_lost);
508        let audio_dropped = obs.audio_send_dropped.saturating_sub(self.last_audio_dropped);
509        self.last_sent = obs.sent_packets;
510        self.last_lost = obs.lost_packets;
511        self.last_audio_dropped = obs.audio_send_dropped;
512        if !self.primed {
513            // The first call sets the baselines; the history before it is not this second's.
514            self.primed = true;
515            return None;
516        }
517        let loss = if sent >= 10 { 100.0 * lost as f32 / sent as f32 } else { 0.0 };
518        let bloated = obs.floor_ms.is_some_and(|f| obs.rtt_ms > f.saturating_add(VIDEO_RTT_BLOAT_MS));
519        // A queue this deep is already costing the voice, which rides behind it.
520        let severe = severe(obs.rtt_ms, obs.floor_ms, loss);
521        // A pinned rung answers only to the voice: the one thing video may never cost.
522        let trouble = if self.pin.is_some() {
523            audio_dropped > 0 || severe
524        } else {
525            loss >= VIDEO_DOWN_AT_PCT || audio_dropped > 0 || bloated || obs.backlog || severe
526        };
527        let ceiling = self.pin.unwrap_or(self.cap);
528        let before = self.rung;
529        if self.hold > 0 {
530            self.hold -= 1;
531        }
532        if severe && self.rung > 0 {
533            // Past what a rung at a time can drain.
534            self.rung = 0;
535            self.clean_secs = 0;
536            self.hold = HOLD_SECS;
537        } else if trouble {
538            self.clean_secs = 0;
539            if self.hold == 0 && self.rung > 0 {
540                self.rung -= 1;
541                self.hold = HOLD_SECS;
542            }
543        } else if loss < CLEAN_PCT {
544            self.clean_secs += 1;
545            if self.clean_secs >= VIDEO_CLIMB_AFTER_SECS && self.rung < ceiling {
546                self.rung += 1;
547                self.clean_secs = 0;
548            }
549        } else {
550            self.clean_secs = 0;
551        }
552        (self.rung != before).then(|| self.rung())
553    }
554}
555
556#[cfg(test)]
557mod video_tests {
558    use super::*;
559
560    fn clean(sent: u64) -> VideoObservation {
561        VideoObservation { sent_packets: sent, lost_packets: 0, rtt_ms: 40, floor_ms: Some(40), audio_send_dropped: 0, backlog: false }
562    }
563
564    #[test]
565    fn a_clean_link_climbs_to_the_cap_and_no_further() {
566        let mut r = VideoRate::camera(CAMERA_RELAY_CAP);
567        assert_eq!(r.rung(), CAMERA_LADDER[4]);
568        let mut sent = 0;
569        let mut changes = 0;
570        for _ in 0..40 {
571            sent += 100;
572            if r.observe(clean(sent)).is_some() {
573                changes += 1;
574            }
575        }
576        assert_eq!(changes, 0, "a relayed camera never passes the relay cap");
577        assert_eq!(r.set_cap(6), None);
578        for _ in 0..VIDEO_CLIMB_AFTER_SECS {
579            sent += 100;
580            r.observe(clean(sent));
581        }
582        assert_eq!(r.rung(), CAMERA_LADDER[5]);
583    }
584
585    #[test]
586    fn audio_drops_and_bufferbloat_step_down_at_once_and_a_cap_pulls_down() {
587        let mut r = VideoRate::camera(6);
588        r.observe(clean(100));
589        r.observe(clean(200));
590        let dropped = VideoObservation { sent_packets: 300, lost_packets: 0, rtt_ms: 40, floor_ms: Some(40), audio_send_dropped: 3, backlog: false };
591        assert_eq!(r.observe(dropped), Some(CAMERA_LADDER[3]));
592        // Held for a few seconds: one bad second costs one rung, not the ladder.
593        let bloat = VideoObservation { sent_packets: 400, lost_packets: 0, rtt_ms: 140, floor_ms: Some(40), audio_send_dropped: 3, backlog: false };
594        assert_eq!(r.observe(bloat), None);
595        let mut sent = 400;
596        for _ in 0..HOLD_SECS {
597            sent += 100;
598            r.observe(VideoObservation { sent_packets: sent, lost_packets: 0, rtt_ms: 140, floor_ms: Some(40), audio_send_dropped: 3, backlog: false });
599        }
600        assert_eq!(r.rung(), CAMERA_LADDER[2]);
601        assert_eq!(r.set_cap(0), Some(CAMERA_LADDER[0]));
602    }
603
604    #[test]
605    fn a_pinned_rung_ignores_loss_but_still_yields_to_the_voice() {
606        let mut r = VideoRate::camera(6);
607        assert_eq!(r.set_pin(Some(6)), Some(CAMERA_LADDER[6]));
608        r.observe(clean(100));
609        let lossy = VideoObservation { sent_packets: 200, lost_packets: 10, rtt_ms: 400, floor_ms: Some(40), audio_send_dropped: 0, backlog: true };
610        assert_eq!(r.observe(lossy), None);
611        let voice = VideoObservation { sent_packets: 300, lost_packets: 10, rtt_ms: 400, floor_ms: Some(40), audio_send_dropped: 1, backlog: true };
612        assert_eq!(r.observe(voice), Some(CAMERA_LADDER[5]));
613        let mut sent = 300;
614        for _ in 0..(HOLD_SECS + VIDEO_CLIMB_AFTER_SECS) {
615            sent += 100;
616            r.observe(VideoObservation { sent_packets: sent, lost_packets: 10, rtt_ms: 400, floor_ms: Some(40), audio_send_dropped: 1, backlog: true });
617        }
618        assert_eq!(r.rung(), CAMERA_LADDER[6], "climbs back to the pin once the voice is fine");
619        assert_eq!(r.set_fps(Some(15)).fps, 15);
620        assert_eq!(r.set_pin(None), None, "unpinning where the ladder already stands changes nothing");
621        // A pin above the path's cap holds: the relay cap is a default, not a rule.
622        let mut relayed = VideoRate::screen(SCREEN_RELAY_CAP);
623        assert_eq!(relayed.set_pin(Some(8)), Some(SCREEN_LADDER[8]));
624        assert_eq!(relayed.set_cap(SCREEN_RELAY_CAP), None);
625        assert_eq!(relayed.rung(), SCREEN_LADDER[8]);
626        assert_eq!(relayed.set_pin(None), Some(SCREEN_LADDER[SCREEN_RELAY_CAP]), "letting go drops back under the cap");
627    }
628
629    #[test]
630    fn a_severe_queue_drops_video_to_the_bottom_even_when_pinned() {
631        let deep = |sent| VideoObservation { sent_packets: sent, lost_packets: 0, rtt_ms: 6000, floor_ms: Some(400), audio_send_dropped: 0, backlog: false };
632        let mut r = VideoRate::screen(SCREEN_RELAY_CAP);
633        r.observe(clean(100));
634        assert_eq!(r.observe(deep(200)), Some(SCREEN_LADDER[0]));
635        let mut pinned = VideoRate::screen(SCREEN_RELAY_CAP);
636        pinned.set_pin(Some(5));
637        pinned.observe(clean(100));
638        assert_eq!(pinned.observe(deep(200)), Some(SCREEN_LADDER[0]), "the queue is already costing the voice");
639        let mut sent = 200;
640        for _ in 0..(HOLD_SECS + VIDEO_CLIMB_AFTER_SECS * 2) {
641            sent += 100;
642            assert_eq!(pinned.observe(deep(sent)), None, "no climbing back while the queue stands");
643        }
644    }
645
646    #[test]
647    fn the_in_flight_budget_stops_growing_at_twice_the_floor() {
648        assert_eq!(budget_rtt(6000, Some(400)), 800);
649        assert_eq!(budget_rtt(550, Some(400)), 550);
650        assert_eq!(budget_rtt(550, None), 550);
651    }
652
653    #[test]
654    fn two_percent_loss_is_enough_for_video() {
655        let mut r = VideoRate::screen(5);
656        r.observe(clean(100));
657        let lossy = VideoObservation { sent_packets: 200, lost_packets: 3, rtt_ms: 40, floor_ms: Some(40), audio_send_dropped: 0, backlog: false };
658        assert_eq!(r.observe(lossy), Some(SCREEN_LADDER[2]));
659    }
660}
661
662#[cfg(test)]
663mod mesh_tests {
664    use super::*;
665
666    fn sample(id: u64, sent: u64, lost: u64) -> LinkSample {
667        LinkSample { id, sent_packets: sent, lost_packets: lost, rtt_ms: 80, relay: true }
668    }
669
670    #[test]
671    fn the_weakest_link_sets_the_rate_and_its_leaving_lifts_it() {
672        let mut mesh = MeshRate::new(START_KBPS);
673        assert_eq!(mesh.observe(&[sample(1, 0, 0), sample(2, 0, 0)]).map(|s| s.kbps), Some(START_KBPS));
674        // Link 2 loses a fifth of a second's fifty frames; link 1 is clean.
675        let down = mesh.observe(&[sample(1, 50, 0), sample(2, 50, 10)]).expect("a lossy link moves the encoder");
676        assert!(down.kbps < START_KBPS, "the encoder follows the lossy link down");
677        assert!(down.fec_pct > FEC_MIN_PCT, "and spends more on FEC");
678        let up = mesh.observe(&[sample(1, 100, 0)]).expect("the lossy link left");
679        assert_eq!(up.kbps, START_KBPS, "the clean link's rung is back at once");
680    }
681
682    #[test]
683    fn a_clean_mesh_never_climbs_past_its_ceiling() {
684        let mut mesh = MeshRate::new(START_KBPS);
685        let mut changes = Vec::new();
686        for sec in 0..120u64 {
687            if let Some(s) = mesh.observe(&[sample(7, sec * 50, 0)]) {
688                changes.push(s.kbps);
689            }
690        }
691        assert!(changes.iter().all(|k| *k <= START_KBPS), "climbing stops at the ceiling: {changes:?}");
692    }
693
694    #[test]
695    fn a_new_link_counts_from_when_it_joined() {
696        let mut mesh = MeshRate::new(START_KBPS);
697        mesh.observe(&[sample(1, 0, 0)]);
698        // A link whose connection already lost packets before the call saw it.
699        assert_eq!(mesh.observe(&[sample(1, 50, 0), sample(3, 9_000, 900)]), None, "its history is not this second's loss");
700    }
701}