diff --git a/crates/client/src/gui.rs b/crates/client/src/gui.rs index e06552d..cea305b 100644 --- a/crates/client/src/gui.rs +++ b/crates/client/src/gui.rs @@ -4,7 +4,7 @@ use std::{ fmt::Display, hash::{DefaultHasher, Hash, Hasher}, sync::Arc, - time::Duration, + time::{Duration, Instant}, }; use common::{ @@ -633,6 +633,8 @@ pub struct Yumush { share_tab: common::share::Kind, camera_modes: Vec, fullscreen: bool, + pumping: bool, + pumped: Instant, send_order: Arc>, } @@ -695,6 +697,8 @@ impl Yumush { share_tab: common::share::Kind::Screen, camera_modes: Vec::new(), fullscreen: false, + pumping: false, + pumped: Instant::now(), send_order: Default::default(), }; yumush.chat.camera_task = Some(camera_view::ticker(cx)); @@ -1393,6 +1397,7 @@ impl Render for Yumush { self.fullscreen = fullscreen; window.toggle_fullscreen(); } + self.schedule_pump(window, cx); let palette = palette(cx); sync_accent(self.themed(cx).accent, cx); let route = self.current_route; diff --git a/crates/client/src/gui/camera_view.rs b/crates/client/src/gui/camera_view.rs index c4fa113..591050b 100644 --- a/crates/client/src/gui/camera_view.rs +++ b/crates/client/src/gui/camera_view.rs @@ -1,4 +1,4 @@ -use std::time::Duration; +use std::time::{Duration, Instant}; use common::model::Id; @@ -10,18 +10,14 @@ use gpui_kit::{ }; use super::{ - Palette, Tooltip as _, Yumush, avatar, clickable, - media_view::into_render_image, - notify_error, - share_view::{self, FRAME_TICK}, - surface::Surface, - text, - wave::mini_wave, - widget::spawn_warn, + Palette, Tooltip as _, Yumush, avatar, clickable, media_view::into_render_image, notify_error, + share_view, surface::Surface, text, wave::mini_wave, widget::spawn_warn, }; use crate::share::session::WatchQuality; const IDLE_TICK: Duration = Duration::from_millis(250); +const FRAME_TICK: Duration = Duration::from_millis(16); +const PUMP_STALL: Duration = Duration::from_millis(50); pub(super) const TILE_QUALITY: WatchQuality = WatchQuality::Fixed(Quality { resolution: Resolution::P360, @@ -296,18 +292,51 @@ impl Yumush { pub(super) fn ticker(cx: &mut Context) -> Task<()> { cx.spawn(async move |this, cx| { - let mut busy = false; + let mut tick = IDLE_TICK; loop { - let tick = if busy { FRAME_TICK } else { IDLE_TICK }; cx.background_executor().timer(tick).await; - match this.update(cx, |yumush, cx| yumush.tick_tiles(cx)) { - Ok(next) => busy = next, + match this.update(cx, |yumush, cx| yumush.idle_tick(cx)) { + Ok(true) => tick = FRAME_TICK, + Ok(false) => tick = IDLE_TICK, Err(_) => break, } } }) } +impl Yumush { + fn streaming(&self) -> bool { + self.chat.viewer.is_some() || !self.chat.tiles.is_empty() + } + + fn pump(&mut self, window: &mut Window, cx: &mut Context) { + self.pumping = false; + self.pumped = Instant::now(); + self.tick_viewer(cx); + self.tick_tiles(cx); + self.schedule_pump(window, cx); + } + + fn idle_tick(&mut self, cx: &mut Context) -> bool { + if self.pumped.elapsed() > PUMP_STALL { + self.tick_viewer(cx); + self.tick_tiles(cx); + } + self.streaming() + } + + pub(super) fn schedule_pump(&mut self, window: &mut Window, cx: &mut Context) { + if self.pumping || !self.streaming() { + return; + } + self.pumping = true; + let this = cx.entity().downgrade(); + window.on_next_frame(move |window, cx| { + let _ = this.update(cx, |yumush, cx| yumush.pump(window, cx)); + }); + } +} + fn stage_tile( entity: &Entity, yumush: &Yumush, diff --git a/crates/client/src/gui/chat.rs b/crates/client/src/gui/chat.rs index b802980..690d02b 100644 --- a/crates/client/src/gui/chat.rs +++ b/crates/client/src/gui/chat.rs @@ -1176,7 +1176,15 @@ impl Chat { pub fn record_share(&mut self, sample: ShareSample) { for (kind, stat) in &sample.sending { - tracing::debug!(target: "metrics", ?kind, kbps = stat.kbps, fps = stat.fps, "send"); + tracing::debug!( + target: "metrics", + ?kind, + kbps = stat.kbps, + fps = stat.fps, + gap50 = stat.gap_ms.0, + gap95 = stat.gap_ms.1, + "send" + ); } for (_, kind, stat) in &sample.watching { tracing::debug!( @@ -1189,6 +1197,11 @@ impl Chat { latency = stat.latency_ms, buffer = stat.buffer_ms, nacks = stat.nacks, + shown = stat.shown_fps, + dropped = stat.dropped, + interval50 = stat.interval_ms.0, + interval95 = stat.interval_ms.1, + swing = stat.swing_ms, "watch" ); } diff --git a/crates/client/src/gui/share_view.rs b/crates/client/src/gui/share_view.rs index 8680263..35410ce 100644 --- a/crates/client/src/gui/share_view.rs +++ b/crates/client/src/gui/share_view.rs @@ -14,7 +14,7 @@ const TOP_QUALITY: Quality = Quality { }; use gpui_kit::{ Anchor, AnyElement, AppContext, Context, Div, Entity, InteractiveElement, IntoElement, - MouseButton, ParentElement, StatefulInteractiveElement, Styled, Subscription, Task, Window, + MouseButton, ParentElement, StatefulInteractiveElement, Styled, Subscription, Window, assets::IconName, component::{ Icon, @@ -50,7 +50,6 @@ use crate::{ const BAR_TTL: Duration = Duration::from_millis(2500); -pub(super) const FRAME_TICK: Duration = Duration::from_millis(16); const RESOLUTIONS: [(Resolution, &str); 6] = [ (Resolution::P360, "360"), (Resolution::P480, "480"), @@ -102,7 +101,6 @@ pub(super) struct Viewer { active: Instant, stats: bool, _subscriptions: Vec, - _tick: Task<()>, } impl Yumush { @@ -297,17 +295,6 @@ impl Yumush { this.update_share(cx, |settings| settings.volume = volume); } })]; - let tick = cx.spawn(async move |this, cx| { - loop { - cx.background_executor().timer(FRAME_TICK).await; - if this - .update(cx, |yumush, cx| yumush.tick_viewer(cx)) - .is_err() - { - break; - } - } - }); self.chat.viewer = Some(Viewer { user_id, @@ -320,7 +307,6 @@ impl Yumush { active: Instant::now(), stats: false, _subscriptions: subscriptions, - _tick: tick, }); let network = self.network.clone(); @@ -377,7 +363,7 @@ impl Yumush { cx.notify(); } - fn tick_viewer(&mut self, cx: &mut Context) { + pub(super) fn tick_viewer(&mut self, cx: &mut Context) { let Some(viewer) = self.chat.viewer.as_mut() else { return; }; diff --git a/crates/client/src/main.rs b/crates/client/src/main.rs index a38d25c..bc1e8dc 100644 --- a/crates/client/src/main.rs +++ b/crates/client/src/main.rs @@ -104,6 +104,7 @@ fn open_window( WindowOptions { window_bounds: Some(WindowBounds::Windowed(window_bounds)), titlebar: Some(titlebar), + inactive_frame_interval: None, ..Default::default() }, |window, cx| { diff --git a/crates/client/src/share/session.rs b/crates/client/src/share/session.rs index f959c29..1186a82 100644 --- a/crates/client/src/share/session.rs +++ b/crates/client/src/share/session.rs @@ -62,6 +62,7 @@ const MAX_DELAY_MS: i64 = 200; const RESYNC_MS: i64 = 2000; const DELAY_MARGIN_MS: i64 = 8; const DELAY_WINDOW_MS: i64 = 1000; +const PRESENT_AHEAD_MS: i64 = 8; const DELAY_DECAY: i64 = 16; const LATENESS_WINDOW: usize = 120; const LATE_MS: i64 = 200; @@ -97,6 +98,7 @@ pub struct LayerStats { pub engine: Engine, pub kbps: u32, pub fps: f32, + pub gap_ms: (i64, i64), } #[derive(Default)] @@ -110,6 +112,10 @@ pub struct WatchStats { pub buffer_ms: i64, pub latency_ms: Option, pub nacks: u32, + pub shown_fps: f32, + pub dropped: u32, + pub interval_ms: (i64, i64), + pub swing_ms: i64, } #[derive(Default)] @@ -122,6 +128,8 @@ struct Tally { engine: Engine, bytes: u64, frames: u32, + last_ms: Option, + gaps: Vec, } struct Sent { @@ -135,9 +143,16 @@ impl Sent { engine: encoded.engine, bytes: 0, frames: 0, + last_ms: None, + gaps: Vec::new(), }); tally.bytes += encoded.data.len() as u64; tally.frames += 1; + if let Some(last) = tally.last_ms.replace(encoded.timestamp_ms) { + tally + .gaps + .push(i64::from(encoded.timestamp_ms) - i64::from(last)); + } } fn take(&mut self) -> Vec { @@ -147,11 +162,12 @@ impl Sent { .max(f32::EPSILON); let mut stats: Vec = std::mem::take(&mut self.tallies) .into_iter() - .map(|(layer, tally)| LayerStats { + .map(|(layer, mut tally)| LayerStats { layer, engine: tally.engine, kbps: (tally.bytes as f32 * 8. / 1000. / seconds) as u32, fps: tally.frames as f32 / seconds, + gap_ms: spread(&mut tally.gaps), }) .collect(); stats.sort_by_key(|stat| stat.layer.to_byte()); @@ -159,6 +175,12 @@ impl Sent { } } +fn spread(values: &mut [i64]) -> (i64, i64) { + values.sort_unstable(); + let at = |part: usize| values.get(values.len() * part / 100).copied().unwrap_or(0); + (at(50), at(95)) +} + fn next(rx: &Receiver, stop: &AtomicBool) -> Option { while !stop.load(Ordering::Relaxed) { match rx.recv_timeout(STOP_CHECK) { @@ -541,6 +563,7 @@ struct Clock { started: Instant, offset: AtomicI64, delay: AtomicI64, + swing: AtomicI64, } impl Clock { @@ -593,9 +616,11 @@ impl Playout { } else { current - ((current - target) / DELAY_DECAY).max(1) }; + let next = next.clamp(MIN_DELAY_MS, MAX_DELAY_MS); + clock.delay.store(next, Ordering::Relaxed); clock - .delay - .store(next.clamp(MIN_DELAY_MS, MAX_DELAY_MS), Ordering::Relaxed); + .swing + .fetch_max((next - current).abs(), Ordering::Relaxed); } fn queuing(&self) -> i64 { @@ -623,6 +648,10 @@ struct Video { queue: VecDeque<(i64, i64, media::Frame)>, generation: u64, decoded: u32, + presented: u32, + dropped: u32, + last_shown: Option, + intervals: Vec, engine: Option, latency_total: i64, latency_count: i64, @@ -689,6 +718,7 @@ impl Watching { started: Instant::now(), offset: AtomicI64::new(i64::MAX), delay: AtomicI64::new(INITIAL_DELAY_MS), + swing: AtomicI64::new(0), }); let video = Arc::new(Mutex::new(Video::default())); let health = Arc::new(Mutex::new(Health::default())); @@ -782,7 +812,7 @@ impl Watching { .as_secs_f32() .max(f32::EPSILON); let bytes = self.received.swap(0, Ordering::Relaxed); - let (decoded, engine, buffer_ms, latency_ms) = { + let (decoded, engine, buffer_ms, latency_ms, presented, dropped, interval_ms) = { let mut video = lock(&self.video); let buffer_ms = match (video.queue.front(), video.queue.back()) { (Some((first, ..)), Some((last, ..))) => last - first, @@ -792,11 +822,16 @@ impl Watching { (video.latency_count > 0).then(|| video.latency_total / video.latency_count); video.latency_total = 0; video.latency_count = 0; + let interval_ms = spread(&mut video.intervals); + video.intervals.clear(); ( std::mem::take(&mut video.decoded), video.engine, buffer_ms, latency_ms, + std::mem::take(&mut video.presented), + std::mem::take(&mut video.dropped), + interval_ms, ) }; let health = lock(&self.health); @@ -810,6 +845,10 @@ impl Watching { buffer_ms, latency_ms, nacks: health.nacks, + shown_fps: presented as f32 / seconds, + dropped, + interval_ms, + swing_ms: self.clock.swing.swap(0, Ordering::Relaxed), } } @@ -817,10 +856,19 @@ impl Watching { let now = self.clock.now(); let mut video = lock(&self.video); let mut due = None; - while video.queue.front().is_some_and(|(at, ..)| *at <= now) { + while video + .queue + .front() + .is_some_and(|(at, ..)| *at <= now + PRESENT_AHEAD_MS) + { + video.dropped += u32::from(due.is_some()); due = video.queue.pop_front(); } let (_, origin, mut frame) = due?; + video.presented += 1; + if let Some(last) = video.last_shown.replace(now) { + video.intervals.push(now - last); + } video.latency_total += now - origin; video.latency_count += 1; video.generation += 1; @@ -1167,6 +1215,7 @@ mod tests { started: Instant::now(), offset: AtomicI64::new(i64::MAX), delay: AtomicI64::new(INITIAL_DELAY_MS), + swing: AtomicI64::new(0), }; clock.observe(116_000); assert!((clock.now() - clock.origin(116_000)).abs() < 50);