Skip to main content

vector_core/calls/
video.rs

1//! The video of a call: frames from the link go out one QUIC stream each, frames
2//! from the peer's streams go back to the webview, and per-track latches keep a lost
3//! or reset frame from ever painting a corrupt picture. A side may send its camera
4//! and its screen at once; every frame's flags say which one it belongs to.
5
6use super::link::{control, parse, FromLink, LinkMsg, ToLink, KIND_FRAME};
7use super::platform::{CallPlatform, LinkConn};
8use super::rate::{budget_rtt, RttFloor, Rung, VideoObservation, VideoRate, CAMERA_LADDER, CAMERA_RELAY_CAP, SCREEN_LADDER, SCREEN_RELAY_CAP};
9use super::share::ShareInput;
10use super::stats::MediaStats;
11use super::wire::{write_control, Control, Tracks, VideoCodec, VideoHeader, VideoKind, MAX_VIDEO_FRAME, VIDEO_HEADER_LEN};
12use bytes::{Bytes, BytesMut};
13use iroh::endpoint::{Connection, SendStream, VarInt};
14use serde::Serialize;
15use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, AtomicUsize, Ordering};
16use std::sync::{Arc, Mutex};
17use std::time::Duration;
18use tokio::sync::mpsc;
19use web_time::Instant;
20
21use crate::rt::time::timeout;
22use crate::rt::JoinHandle;
23
24/// Frames on the wire at once before captures are skipped, at a zero round trip. A
25/// frame counts as on the wire until the peer has acknowledged all of it, so the
26/// cap grows with the round trip: what a path holds in one RTT, and a little over.
27const IN_FLIGHT_MIN: usize = 4;
28/// Time past the round trip before a frame's stream is acknowledged: the peer's ACK
29/// delay and the read on its side.
30const ACK_SLACK_MS: usize = 60;
31/// Captures skipped in a second, as a share of the rung's rate, that read as a wire
32/// too full for the rung. A skip now and then is the cap doing its job.
33const BACKLOG_SKIP_SHARE: u64 = 4;
34/// A delta the peer has not acknowledged by then is reset: it is a picture of the
35/// past. Also scaled by the round trip, and a keyframe gets longer, since resetting
36/// one only buys another.
37const STALE_MIN: Duration = Duration::from_millis(400);
38const STALE_KEY_MIN: Duration = Duration::from_secs(2);
39/// Keyframes cost tens of kilobytes; requests coalesce to this many, in both directions.
40const KEYFRAME_MIN_GAP: Duration = Duration::from_secs(1);
41/// A frame the peer takes longer than this to deliver is abandoned; the next keyframe restarts.
42const INBOUND_FRAME_TIMEOUT: Duration = Duration::from_secs(2);
43/// How long a received frame waits for the webview before it is dropped.
44const TO_WEB_WAIT: Duration = Duration::from_millis(250);
45/// With the screen on as well, the camera is a thumbnail: it gets this rung at most.
46const CAMERA_BESIDE_SCREEN_CAP: usize = 2;
47
48const KINDS: [VideoKind; 2] = [VideoKind::Camera, VideoKind::Screen];
49
50/// One encoder's own numbers, as the webview reports them.
51#[derive(Default)]
52pub struct TrackStats {
53    pub fps: AtomicU32,
54    pub kbps: AtomicU32,
55    pub width: AtomicU32,
56    pub height: AtomicU32,
57}
58
59#[derive(Default)]
60pub struct VideoStats {
61    pub sent: AtomicU64,
62    pub bytes_out: AtomicU64,
63    pub skipped: AtomicU64,
64    pub stale: AtomicU64,
65    pub received: AtomicU64,
66    pub bytes_in: AtomicU64,
67    pub dropped: AtomicU64,
68    pub key_requests: AtomicU64,
69    pub camera: TrackStats,
70    pub screen: TrackStats,
71}
72
73#[derive(Serialize, Clone, Debug, Default)]
74pub struct TrackSnapshot {
75    pub fps: u32,
76    pub kbps: u32,
77    pub width: u32,
78    pub height: u32,
79    /// The rung the ladder is on, and how many it has; the panel's quality control.
80    pub rung: u32,
81    pub rungs: u32,
82    pub pinned: bool,
83}
84
85/// The stats line's view of the video.
86#[derive(Serialize, Clone, Debug, Default)]
87pub struct VideoSnapshot {
88    pub sent: u64,
89    pub bytes_out: u64,
90    pub skipped: u64,
91    pub stale: u64,
92    pub received: u64,
93    pub bytes_in: u64,
94    pub dropped: u64,
95    pub key_requests: u64,
96    pub camera: TrackSnapshot,
97    pub screen: TrackSnapshot,
98}
99
100impl VideoStats {
101    fn track(&self, kind: VideoKind) -> &TrackStats {
102        match kind {
103            VideoKind::Camera => &self.camera,
104            VideoKind::Screen => &self.screen,
105        }
106    }
107}
108
109/// What the track needs from the session while it runs.
110pub struct Hooks {
111    pub call_id: String,
112    /// The call's control stream, for keyframe requests.
113    pub control: Arc<tokio::sync::Mutex<SendStream>>,
114    /// The webview's socket went away: the session tells the peer our video is off.
115    pub on_link_closed: Arc<dyn Fn(&str) + Send + Sync>,
116    /// The webview reported what it can encode and decode.
117    pub on_caps: Arc<dyn Fn(Vec<String>, Vec<String>) + Send + Sync>,
118    /// The audio track's counters: its refused datagrams are video's first alarm.
119    pub audio: Arc<MediaStats>,
120    /// The peer declared decoders in its offer or answer. A peer that did not runs a
121    /// build whose control reader stops at the first message it does not know, so
122    /// it is never sent one.
123    pub peer_video: bool,
124    /// Where the shared screen's sound goes on its way to the engine.
125    pub share: Arc<ShareInput>,
126}
127
128/// The user's choices for one track: a held rung, a held frame rate, or neither.
129#[derive(Clone, Copy, Default)]
130pub struct Prefs {
131    pub rung: Option<usize>,
132    pub fps: Option<u32>,
133}
134
135struct Shared {
136    stats: Arc<VideoStats>,
137    to_web: Mutex<Option<mpsc::Sender<Bytes>>>,
138    in_flight: AtomicUsize,
139    /// That track's next outgoing frame must be a keyframe: a delta was reset.
140    need_key_out: [AtomicBool; 2],
141    /// Drop that track's incoming deltas until a keyframe: the chain broke, or the
142    /// webview just reconnected.
143    need_key_in: [AtomicBool; 2],
144    last_key_request: [Mutex<Option<Instant>>; 2],
145    /// The peer's keyframe requests are honoured this often at most.
146    last_key_forced: [Mutex<Option<Instant>>; 2],
147    codec: Mutex<Option<VideoCodec>>,
148    peer: Mutex<Tracks>,
149    /// The peer declared decoders, so it runs a build that knows the video messages.
150    peer_video: AtomicBool,
151    conn: Connection,
152    /// One ladder per track we send; None while that track is off.
153    rate: Mutex<[Option<VideoRate>; 2]>,
154    prefs: Mutex<[Prefs; 2]>,
155    /// The selected path's round-trip floor, in ms (0 until it has one).
156    floor_ms: AtomicU32,
157}
158
159impl Shared {
160    fn tell_web(&self, msg: &ToLink) {
161        let tx = self.to_web.lock().unwrap_or_else(|e| e.into_inner()).clone();
162        if let Some(tx) = tx {
163            let _ = tx.try_send(Bytes::from(control(msg)));
164        }
165    }
166
167    /// Whether the selected path goes through a relay, and its round trip.
168    fn path(&self) -> (bool, u32) {
169        let paths = self.conn.paths();
170        match paths.iter().find(|p| p.is_selected()).or_else(|| paths.iter().next()) {
171            Some(p) => (p.is_relay(), p.rtt().as_millis() as u32),
172            None => (true, 0),
173        }
174    }
175
176    fn tell_rung(&self, kind: VideoKind, r: Rung) {
177        self.tell_web(&ToLink::Rate { kind, kbps: r.kbps, width: r.width, height: r.height, fps: r.fps });
178    }
179
180    /// Frames per second across everything we send, for the in-flight cap.
181    fn sending_fps(&self) -> usize {
182        let rates = self.rate.lock().unwrap_or_else(|e| e.into_inner());
183        rates.iter().flatten().map(|r| r.rung().fps as usize).sum::<usize>().max(1)
184    }
185
186    /// How many frames may be unacknowledged before captures are skipped: one
187    /// acknowledgement's worth at the sending rate, plus a little, never under the
188    /// floor. An acknowledgement takes the round trip plus the peer's ACK delay and
189    /// its read, so a cap sized to the round trip alone sits full on a clean link.
190    fn in_flight_cap(&self, rtt_ms: u32) -> usize {
191        let floor = Some(self.floor_ms.load(Ordering::Relaxed)).filter(|&f| f > 0);
192        let rtt = budget_rtt(rtt_ms, floor) as usize;
193        ((rtt + ACK_SLACK_MS) * self.sending_fps() / 1000 + 2).max(IN_FLIGHT_MIN)
194    }
195
196    /// The ceiling a track gets on this path, and beside its sibling.
197    fn cap_for(&self, kind: VideoKind, relay: bool, both: bool) -> usize {
198        match kind {
199            VideoKind::Camera => {
200                let cap = if relay { CAMERA_RELAY_CAP } else { CAMERA_LADDER.len() - 1 };
201                if both { cap.min(CAMERA_BESIDE_SCREEN_CAP) } else { cap }
202            }
203            VideoKind::Screen => {
204                if relay { SCREEN_RELAY_CAP } else { SCREEN_LADDER.len() - 1 }
205            }
206        }
207    }
208}
209
210pub struct VideoTrack {
211    shared: Arc<Shared>,
212    platform: Arc<dyn CallPlatform>,
213    tasks: Vec<JoinHandle<()>>,
214    pub stats: Arc<VideoStats>,
215}
216
217impl VideoTrack {
218    pub fn start(conn: Connection, hooks: Hooks, platform: Arc<dyn CallPlatform>) -> Self {
219        let stats = Arc::new(VideoStats::default());
220        let hooks = Arc::new(hooks);
221        let shared = Arc::new(Shared {
222            stats: Arc::clone(&stats),
223            to_web: Mutex::new(None),
224            in_flight: AtomicUsize::new(0),
225            need_key_out: [AtomicBool::new(false), AtomicBool::new(false)],
226            need_key_in: [AtomicBool::new(true), AtomicBool::new(true)],
227            last_key_request: [Mutex::new(None), Mutex::new(None)],
228            last_key_forced: [Mutex::new(None), Mutex::new(None)],
229            codec: Mutex::new(None),
230            peer: Mutex::new(Tracks::default()),
231            peer_video: AtomicBool::new(hooks.peer_video),
232            conn: conn.clone(),
233            rate: Mutex::new([None, None]),
234            prefs: Mutex::new([Prefs::default(), Prefs::default()]),
235            floor_ms: AtomicU32::new(0),
236        });
237        let (taker_tx, taker_rx) = mpsc::channel::<LinkConn>(1);
238        platform.set_video_taker(Some(taker_tx));
239
240        let out = {
241            let shared = Arc::clone(&shared);
242            let hooks = Arc::clone(&hooks);
243            let conn = conn.clone();
244            crate::db::spawn_bound(async move { outbound(conn, shared, hooks, taker_rx).await })
245        };
246        let inn = {
247            let shared = Arc::clone(&shared);
248            let hooks = Arc::clone(&hooks);
249            let conn = conn.clone();
250            crate::db::spawn_bound(async move { inbound(conn, shared, hooks).await })
251        };
252        let rate = {
253            let shared = Arc::clone(&shared);
254            let hooks = Arc::clone(&hooks);
255            crate::db::spawn_bound(async move { rate_loop(conn, shared, hooks).await })
256        };
257        Self { shared, platform, tasks: vec![out, inn, rate], stats }
258    }
259
260    /// What we send from now on. A track that turns on gets a fresh ladder on a rung
261    /// the path allows (and the user's pin, if any), and the webview hears its size
262    /// and rate before any frame; a sibling's ceiling moves when the pair changes.
263    pub fn set_sending(&self, tracks: Tracks) {
264        let (relay, _) = self.shared.path();
265        let prefs = *self.shared.prefs.lock().unwrap_or_else(|e| e.into_inner());
266        let mut rates = self.shared.rate.lock().unwrap_or_else(|e| e.into_inner());
267        let both = tracks.camera && tracks.screen;
268        for kind in KINDS {
269            let i = kind.index();
270            let cap = self.shared.cap_for(kind, relay, both);
271            match (tracks.has(kind), rates[i].as_mut()) {
272                (false, _) => rates[i] = None,
273                (true, Some(rate)) => {
274                    if let Some(r) = rate.set_cap(cap) {
275                        self.shared.tell_rung(kind, r);
276                    }
277                }
278                (true, None) => {
279                    let mut rate = match kind {
280                        VideoKind::Camera => VideoRate::camera(cap),
281                        VideoKind::Screen => VideoRate::screen(cap),
282                    };
283                    rate.set_pin(prefs[i].rung);
284                    rate.set_fps(prefs[i].fps);
285                    self.shared.tell_rung(kind, rate.rung());
286                    self.shared.need_key_out[i].store(true, Ordering::Relaxed);
287                    rates[i] = Some(rate);
288                }
289            }
290        }
291    }
292
293    /// The user's choice for a track, kept for the next time it turns on too.
294    pub fn set_prefs(&self, kind: VideoKind, prefs: Prefs) {
295        let i = kind.index();
296        self.shared.prefs.lock().unwrap_or_else(|e| e.into_inner())[i] = prefs;
297        let mut rates = self.shared.rate.lock().unwrap_or_else(|e| e.into_inner());
298        if let Some(rate) = rates[i].as_mut() {
299            let moved = rate.set_pin(prefs.rung);
300            let r = rate.set_fps(prefs.fps);
301            let _ = moved;
302            self.shared.tell_rung(kind, r);
303        }
304    }
305
306    /// The codec the peer decodes; told to the webview whenever it connects.
307    pub fn set_codec(&self, codec: VideoCodec) {
308        *self.shared.codec.lock().unwrap_or_else(|e| e.into_inner()) = Some(codec);
309        self.shared.tell_web(&ToLink::Codec { codec });
310    }
311
312    pub fn set_peer(&self, tracks: Tracks) {
313        let before = std::mem::replace(&mut *self.shared.peer.lock().unwrap_or_else(|e| e.into_inner()), tracks);
314        for kind in KINDS {
315            // A track that went off and comes back starts a fresh chain.
316            if before.has(kind) && !tracks.has(kind) {
317                self.shared.need_key_in[kind.index()].store(true, Ordering::Relaxed);
318            }
319        }
320        self.shared.tell_web(&ToLink::Peer { tracks });
321    }
322
323    /// The peer cannot see us (or can again).
324    pub fn set_paused(&self, on: bool) {
325        self.shared.tell_web(&ToLink::Pause { on });
326    }
327
328    /// The peer asked for a keyframe on that track. Honoured once a second: a peer
329    /// asking at wire rate would otherwise turn every frame into a keyframe.
330    pub fn force_keyframe(&self, kind: VideoKind) {
331        let i = kind.index();
332        {
333            let mut last = self.shared.last_key_forced[i].lock().unwrap_or_else(|e| e.into_inner());
334            if last.is_some_and(|t| t.elapsed() < KEYFRAME_MIN_GAP) {
335                return;
336            }
337            *last = Some(Instant::now());
338        }
339        self.shared.need_key_out[i].store(true, Ordering::Relaxed);
340        self.shared.tell_web(&ToLink::Keyframe { kind });
341    }
342
343    /// The panel's view of each track's ladder.
344    pub fn snapshot(&self) -> VideoSnapshot {
345        let l = |a: &AtomicU64| a.load(Ordering::Relaxed);
346        let rates = self.shared.rate.lock().unwrap_or_else(|e| e.into_inner());
347        let prefs = self.shared.prefs.lock().unwrap_or_else(|e| e.into_inner());
348        let track = |kind: VideoKind| {
349            let i = kind.index();
350            let t = self.stats.track(kind);
351            let (rung, rungs) = rates[i].as_ref().map_or((0, 0), |r| {
352                let current = r.rung();
353                let ladder: &[Rung] = if r.is_camera() { &CAMERA_LADDER } else { &SCREEN_LADDER };
354                let idx = ladder.iter().position(|x| x.kbps == current.kbps).unwrap_or(0);
355                (idx as u32, r.rungs() as u32)
356            });
357            TrackSnapshot {
358                fps: t.fps.load(Ordering::Relaxed),
359                kbps: t.kbps.load(Ordering::Relaxed),
360                width: t.width.load(Ordering::Relaxed),
361                height: t.height.load(Ordering::Relaxed),
362                rung,
363                rungs,
364                pinned: prefs[i].rung.is_some(),
365            }
366        };
367        VideoSnapshot {
368            sent: l(&self.stats.sent),
369            bytes_out: l(&self.stats.bytes_out),
370            skipped: l(&self.stats.skipped),
371            stale: l(&self.stats.stale),
372            received: l(&self.stats.received),
373            bytes_in: l(&self.stats.bytes_in),
374            dropped: l(&self.stats.dropped),
375            key_requests: l(&self.stats.key_requests),
376            camera: track(VideoKind::Camera),
377            screen: track(VideoKind::Screen),
378        }
379    }
380}
381
382impl Drop for VideoTrack {
383    fn drop(&mut self) {
384        self.platform.set_video_taker(None);
385        for t in self.tasks.drain(..) {
386            t.abort();
387        }
388        // Dropping the sender closes the webview's socket, which stops its captures.
389        self.shared.to_web.lock().unwrap_or_else(|e| e.into_inner()).take();
390    }
391}
392
393/// Sockets from the webview, one at a time; each one's frames go out on the connection.
394async fn outbound(conn: Connection, shared: Arc<Shared>, hooks: Arc<Hooks>, mut taker: mpsc::Receiver<LinkConn>) {
395    while let Some(mut link) = taker.recv().await {
396        *shared.to_web.lock().unwrap_or_else(|e| e.into_inner()) = Some(link.to_web.clone());
397        // Fresh decoders on the other side of the socket need keyframes to start on.
398        for kind in KINDS {
399            shared.need_key_in[kind.index()].store(true, Ordering::Relaxed);
400            request_keyframe(&shared, &hooks, kind).await;
401        }
402        let codec = *shared.codec.lock().unwrap_or_else(|e| e.into_inner());
403        if let Some(codec) = codec {
404            shared.tell_web(&ToLink::Codec { codec });
405        }
406        let tracks = *shared.peer.lock().unwrap_or_else(|e| e.into_inner());
407        shared.tell_web(&ToLink::Peer { tracks });
408        {
409            let rates = shared.rate.lock().unwrap_or_else(|e| e.into_inner());
410            for kind in KINDS {
411                if let Some(r) = rates[kind.index()].as_ref() {
412                    shared.tell_rung(kind, r.rung());
413                }
414            }
415        }
416
417        while let Some(msg) = link.from_web.recv().await {
418            match parse(&msg) {
419                Some(LinkMsg::Frame { header, .. }) => {
420                    ship(&conn, &shared, msg.slice(1..), header).await;
421                }
422                Some(LinkMsg::Pcm { rate, channels, samples }) => {
423                    let pcm: Vec<f32> = samples.chunks_exact(4).map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect();
424                    hooks.share.push(rate, channels, &pcm);
425                }
426                Some(LinkMsg::Control(c)) => match c {
427                    FromLink::Caps { encode, decode } => (hooks.on_caps)(encode, decode),
428                    FromLink::Stats { kind, fps, kbps, width, height } => {
429                        let t = shared.stats.track(kind);
430                        t.fps.store(fps, Ordering::Relaxed);
431                        t.kbps.store(kbps, Ordering::Relaxed);
432                        t.width.store(width, Ordering::Relaxed);
433                        t.height.store(height, Ordering::Relaxed);
434                    }
435                    FromLink::Lost { kind } => {
436                        shared.need_key_in[kind.index()].store(true, Ordering::Relaxed);
437                        request_keyframe(&shared, &hooks, kind).await;
438                    }
439                    FromLink::Unsupported { codec, .. } => {
440                        if shared.peer_video.load(Ordering::Relaxed) {
441                            let mut send = hooks.control.lock().await;
442                            let _ = timeout(Duration::from_secs(1), write_control(&mut *send, &Control::VideoUnsupported { codec })).await;
443                        }
444                    }
445                    FromLink::LostFrom { .. } | FromLink::Unknown => {}
446                },
447                None => {}
448            }
449        }
450        shared.to_web.lock().unwrap_or_else(|e| e.into_inner()).take();
451        (hooks.on_link_closed)(&hooks.call_id);
452    }
453}
454
455/// One frame onto one stream. The stream is opened here, in frame order, because
456/// the peer reads streams in the order their ids were issued and a delta that
457/// overtakes its predecessor reads as a gap; only the write and the wait for the
458/// acknowledgement run on a task of their own, so a slow frame never holds the next.
459async fn ship(conn: &Connection, shared: &Arc<Shared>, frame: Bytes, header: VideoHeader) {
460    let kind = VideoKind::from_flags(header.flags);
461    let i = kind.index();
462    if shared.need_key_out[i].load(Ordering::Relaxed) {
463        if header.is_key() {
464            shared.need_key_out[i].store(false, Ordering::Relaxed);
465        } else {
466            shared.stats.skipped.fetch_add(1, Ordering::Relaxed);
467            return;
468        }
469    }
470    let (_, rtt_ms) = shared.path();
471    let cap = shared.in_flight_cap(rtt_ms);
472    // An encoded frame is never dropped: a delta the peer never sees breaks the chain.
473    // Instead the webview is told to skip captures while the wire is this full, so
474    // what it drops was never encoded.
475    if shared.in_flight.load(Ordering::Relaxed) + 1 >= cap {
476        shared.stats.skipped.fetch_add(1, Ordering::Relaxed);
477        shared.tell_web(&ToLink::Skip { kind });
478    }
479    shared.in_flight.fetch_add(1, Ordering::Relaxed);
480    let conn = conn.clone();
481    let shared = Arc::clone(shared);
482    let len = frame.len() as u64;
483    let key = header.is_key();
484    let rtt = Duration::from_millis(rtt_ms as u64);
485    let stale = if key { STALE_KEY_MIN.max(rtt * 4) } else { STALE_MIN.max(rtt * 3) };
486    let t0 = Instant::now();
487    let opened = timeout(stale, conn.open_uni()).await;
488    let mut s = match opened {
489        Ok(Ok(s)) => s,
490        other => {
491            crate::log_info!("[VIDEO] stale: open_uni {} after {} ms, key {key}, {len} bytes", if other.is_err() { "timed out" } else { "failed" }, t0.elapsed().as_millis());
492            shared.in_flight.fetch_sub(1, Ordering::Relaxed);
493            shared.stats.stale.fetch_add(1, Ordering::Relaxed);
494            shared.need_key_out[i].store(true, Ordering::Relaxed);
495            shared.tell_web(&ToLink::Keyframe { kind });
496            return;
497        }
498    };
499    let _ = s.set_priority(if key { 1 } else { 0 });
500    crate::db::spawn_bound(async move {
501        let result = async {
502            if timeout(stale, s.write_chunk(frame)).await.is_err() {
503                let _ = s.reset(VarInt::from_u32(1));
504                return Err("write");
505            }
506            if s.finish().is_err() {
507                return Err("finish");
508            }
509            if timeout(stale, s.stopped()).await.is_err() {
510                let _ = s.reset(VarInt::from_u32(1));
511                return Err("stale");
512            }
513            Ok(())
514        }
515        .await;
516        shared.in_flight.fetch_sub(1, Ordering::Relaxed);
517        match result {
518            Ok(()) => {
519                shared.stats.sent.fetch_add(1, Ordering::Relaxed);
520                shared.stats.bytes_out.fetch_add(len, Ordering::Relaxed);
521            }
522            Err(reason) => {
523                crate::log_info!("[VIDEO] stale: {reason} after {} ms, key {key}, {len} bytes", t0.elapsed().as_millis());
524                shared.stats.stale.fetch_add(1, Ordering::Relaxed);
525                shared.need_key_out[i].store(true, Ordering::Relaxed);
526                shared.tell_web(&ToLink::Keyframe { kind });
527            }
528        }
529    });
530}
531
532/// Once a second while we send: the connection's own loss and round trip, the audio
533/// track's refused datagrams and our own backlog decide each rung; the path's kind
534/// decides the ceilings.
535async fn rate_loop(conn: Connection, shared: Arc<Shared>, hooks: Arc<Hooks>) {
536    let mut last_stale = 0u64;
537    let mut last_skipped = 0u64;
538    let mut last_sent = 0u64;
539    let mut last_received = 0u64;
540    let mut tick = 0u32;
541    let mut was_relay: Option<bool> = None;
542    let mut floor = RttFloor::default();
543    loop {
544        crate::rt::time::sleep(Duration::from_secs(1)).await;
545        let (relay, rtt_ms) = shared.path();
546        let floor_ms = floor.observe(rtt_ms, relay);
547        shared.floor_ms.store(floor_ms.unwrap_or(0), Ordering::Relaxed);
548        let stale = shared.stats.stale.load(Ordering::Relaxed);
549        let skipped = shared.stats.skipped.load(Ordering::Relaxed);
550        let sent = shared.stats.sent.load(Ordering::Relaxed);
551        let in_flight = shared.in_flight.load(Ordering::Relaxed);
552        let cap = shared.in_flight_cap(rtt_ms);
553        // Backlog is a frame that timed out, or a second in which the cap turned away a
554        // real share of the captures; a sample of the in-flight count is the cap working.
555        let fps = shared.sending_fps() as u64;
556        let backlog = stale > last_stale || (skipped - last_skipped) * BACKLOG_SKIP_SHARE > fps;
557        tick += 1;
558        let received = shared.stats.received.load(Ordering::Relaxed);
559        if tick.is_multiple_of(2) && (sent != last_sent || received != last_received) {
560            let net = conn.stats();
561            let (cwnd, cong) = {
562                let paths = conn.paths();
563                paths
564                    .iter()
565                    .find(|p| p.is_selected())
566                    .or_else(|| paths.iter().next())
567                    .map(|p| {
568                        let s = p.stats();
569                        (s.cwnd, s.congestion_events)
570                    })
571                    .unwrap_or((0, 0))
572            };
573            let rung = {
574                let rates = shared.rate.lock().unwrap_or_else(|e| e.into_inner());
575                rates.iter().flatten().map(|r| r.rung()).map(|r| format!("{}fps/{}kbps", r.fps, r.kbps)).collect::<Vec<_>>().join("+")
576            };
577            crate::log_info!(
578                "[VIDEO] rtt {rtt_ms} ms (floor {floor_ms:?}) {} cwnd {} lost {} cong {} | blocked: data {} stream_data {} streams_uni {} | out: sent {} skipped {} stale {} in_flight {in_flight}/{cap} rung {rung} | in: received {received} dropped {} key_req {}",
579                if relay { "relay" } else { "direct" },
580                cwnd,
581                net.lost_packets,
582                cong,
583                net.frame_tx.data_blocked,
584                net.frame_tx.stream_data_blocked,
585                net.frame_tx.streams_blocked_uni,
586                sent - last_sent,
587                skipped - last_skipped,
588                stale - last_stale,
589                shared.stats.dropped.load(Ordering::Relaxed),
590                shared.stats.key_requests.load(Ordering::Relaxed),
591            );
592            last_sent = sent;
593            last_received = received;
594        }
595        last_stale = stale;
596        last_skipped = skipped;
597        let net = conn.stats();
598        let obs = VideoObservation {
599            sent_packets: net.udp_tx.datagrams,
600            lost_packets: net.lost_packets,
601            rtt_ms,
602            floor_ms,
603            audio_send_dropped: hooks.audio.send_dropped.load(Ordering::Relaxed),
604            backlog,
605        };
606        let path_changed = was_relay != Some(relay);
607        was_relay = Some(relay);
608        // A latch must not wait forever on a message that was lost or never answered:
609        // a track we send that still owes a keyframe is told again, and a track we
610        // receive that is still waiting for one asks again.
611        let peer = *shared.peer.lock().unwrap_or_else(|e| e.into_inner());
612        for kind in KINDS {
613            let i = kind.index();
614            if shared.need_key_out[i].load(Ordering::Relaxed) {
615                shared.tell_web(&ToLink::Keyframe { kind });
616            }
617            if peer.has(kind) && shared.need_key_in[i].load(Ordering::Relaxed) {
618                request_keyframe(&shared, &hooks, kind).await;
619            }
620        }
621        let mut changes: Vec<(VideoKind, Rung)> = Vec::new();
622        {
623            let mut rates = shared.rate.lock().unwrap_or_else(|e| e.into_inner());
624            let both = rates.iter().all(|r| r.is_some());
625            for kind in KINDS {
626                let Some(rate) = rates[kind.index()].as_mut() else { continue };
627                let capped = if path_changed { rate.set_cap(shared.cap_for(kind, relay, both)) } else { None };
628                if let Some(r) = rate.observe(obs).or(capped) {
629                    changes.push((kind, r));
630                }
631            }
632        }
633        for (kind, r) in changes {
634            shared.tell_rung(kind, r);
635        }
636    }
637}
638
639async fn request_keyframe(shared: &Shared, hooks: &Hooks, kind: VideoKind) {
640    if !shared.peer_video.load(Ordering::Relaxed) {
641        return;
642    }
643    {
644        let mut last = shared.last_key_request[kind.index()].lock().unwrap_or_else(|e| e.into_inner());
645        if last.is_some_and(|t| t.elapsed() < KEYFRAME_MIN_GAP) {
646            return;
647        }
648        *last = Some(Instant::now());
649    }
650    shared.stats.key_requests.fetch_add(1, Ordering::Relaxed);
651    let mut send = hooks.control.lock().await;
652    let _ = timeout(Duration::from_secs(1), write_control(&mut *send, &Control::KeyframeRequest { kind })).await;
653}
654
655/// The peer's streams, in order, each one a frame for the webview.
656async fn inbound(conn: Connection, shared: Arc<Shared>, hooks: Arc<Hooks>) {
657    let mut next_seq: [Option<u32>; 2] = [None, None];
658    loop {
659        let Ok(mut stream) = conn.accept_uni().await else { break };
660        let mut buf = BytesMut::with_capacity(VIDEO_HEADER_LEN + 1 + 64 * 1024);
661        buf.extend_from_slice(&[KIND_FRAME]);
662        let mut whole = true;
663        let deadline = Instant::now() + INBOUND_FRAME_TIMEOUT;
664        loop {
665            let left = deadline.saturating_duration_since(Instant::now());
666            let read = match timeout(left, stream.read_chunk(MAX_VIDEO_FRAME)).await {
667                Ok(r) => r,
668                Err(_) => {
669                    let _ = stream.stop(VarInt::from_u32(3));
670                    whole = false;
671                    break;
672                }
673            };
674            match read {
675                Ok(Some(chunk)) => {
676                    if buf.len() + chunk.len() > MAX_VIDEO_FRAME + 1 {
677                        let _ = stream.stop(VarInt::from_u32(2));
678                        whole = false;
679                        break;
680                    }
681                    buf.extend_from_slice(&chunk);
682                }
683                Ok(None) => break,
684                Err(_) => {
685                    whole = false;
686                    break;
687                }
688            }
689        }
690        // A reset or oversized frame still says which track it was if its header
691        // arrived; without one, both chains restart on their next keyframe.
692        let Some(header) = VideoHeader::parse(&buf[1..]) else {
693            shared.stats.dropped.fetch_add(1, Ordering::Relaxed);
694            for kind in KINDS {
695                shared.need_key_in[kind.index()].store(true, Ordering::Relaxed);
696                request_keyframe(&shared, &hooks, kind).await;
697            }
698            continue;
699        };
700        let kind = VideoKind::from_flags(header.flags);
701        let i = kind.index();
702        if !whole {
703            shared.stats.dropped.fetch_add(1, Ordering::Relaxed);
704            shared.need_key_in[i].store(true, Ordering::Relaxed);
705            request_keyframe(&shared, &hooks, kind).await;
706            continue;
707        }
708        if let Some(expected) = next_seq[i] {
709            if header.seq != expected && !header.is_key() {
710                shared.need_key_in[i].store(true, Ordering::Relaxed);
711            }
712        }
713        next_seq[i] = Some(header.seq.wrapping_add(1));
714        if shared.need_key_in[i].load(Ordering::Relaxed) {
715            if header.is_key() {
716                shared.need_key_in[i].store(false, Ordering::Relaxed);
717            } else {
718                shared.stats.dropped.fetch_add(1, Ordering::Relaxed);
719                request_keyframe(&shared, &hooks, kind).await;
720                continue;
721            }
722        }
723        let len = buf.len() as u64;
724        let tx = shared.to_web.lock().unwrap_or_else(|e| e.into_inner()).clone();
725        // Wait for the webview rather than drop: a dropped delta costs a keyframe, and
726        // a keyframe a second is a slideshow. Waiting holds the stream unread, which
727        // holds the sender's acknowledgement, which is what makes it skip captures.
728        let delivered = match tx {
729            Some(tx) => timeout(TO_WEB_WAIT, tx.send(buf.freeze())).await.is_ok_and(|r| r.is_ok()),
730            None => false,
731        };
732        if delivered {
733            shared.stats.received.fetch_add(1, Ordering::Relaxed);
734            shared.stats.bytes_in.fetch_add(len, Ordering::Relaxed);
735        } else {
736            // The webview is not keeping up (or is not there): resume on a keyframe.
737            shared.stats.dropped.fetch_add(1, Ordering::Relaxed);
738            shared.need_key_in[i].store(true, Ordering::Relaxed);
739        }
740    }
741}