diff --git a/crates/client/src/gui/camera_view.rs b/crates/client/src/gui/camera_view.rs index 0a6c105..c4fa113 100644 --- a/crates/client/src/gui/camera_view.rs +++ b/crates/client/src/gui/camera_view.rs @@ -435,6 +435,7 @@ fn grid_cell( if shared { let entity = entity.clone(); cell.cursor_pointer() + .tip("Watch") .on_click(move |_, window, cx| { entity.update(cx, |yumush, cx| { yumush.toggle_viewer(user_id, kind, window, cx) diff --git a/crates/client/src/gui/chat.rs b/crates/client/src/gui/chat.rs index 80fda0f..92c1ea6 100644 --- a/crates/client/src/gui/chat.rs +++ b/crates/client/src/gui/chat.rs @@ -253,9 +253,12 @@ pub struct Chat { pub(super) voice_task: Option>, pub(super) user_volume: Option, pub(super) voice_samples: VecDeque, + pub(super) traffic: VecDeque<(f32, f32)>, pub(super) share_sample: ShareSample, pub(super) share_loss: HashMap<(Id, Kind), VecDeque>, pub(super) stats_open: bool, + pub(super) usage: Option, + pub(super) usage_sampler: crate::usage::Sampler, pub(super) ringing: HashSet, pub(super) ring_task: Option>, pub(super) media: Media, @@ -495,9 +498,12 @@ impl Chat { builder_voice_rooms: Vec::new(), voice_task: None, voice_samples: VecDeque::new(), + traffic: VecDeque::new(), share_sample: ShareSample::default(), share_loss: HashMap::new(), stats_open: false, + usage: None, + usage_sampler: crate::usage::Sampler::default(), ringing: HashSet::new(), ring_task: None, typing: HashMap::new(), @@ -1163,6 +1169,7 @@ impl Chat { self.waves.clear(); self.voice_task = None; self.voice_samples.clear(); + self.traffic.clear(); self.share_sample = ShareSample::default(); self.share_loss.clear(); } @@ -1364,7 +1371,7 @@ impl Yumush { (self.chat.stats_open && self.in_stage_chat()).then(|| { div() .id("stats_side") - .w(px(340.)) + .w(px(380.)) .flex_shrink_0() .p(px(10.)) .border_l_1() @@ -2258,6 +2265,25 @@ impl Yumush { if yumush.chat.voice_community().is_none() { return false; } + if let (Some(sample), Some(share)) = (&sample, &share) { + let up = sample.traffic.up_kbps + + share + .sending + .iter() + .map(|(_, layer)| layer.kbps as f32) + .sum::(); + let down = sample.traffic.down_kbps + + share + .watching + .iter() + .map(|(_, _, stats)| stats.kbps as f32) + .sum::(); + let traffic = &mut yumush.chat.traffic; + traffic.push_back((up, down)); + while traffic.len() > SAMPLE_HISTORY { + traffic.pop_front(); + } + } if let Some(sample) = sample { let samples = &mut yumush.chat.voice_samples; tracing::debug!( @@ -2278,6 +2304,9 @@ impl Yumush { yumush.chat.record_share(share); cx.notify(); } + if due && yumush.chat.stats_open { + yumush.chat.usage = yumush.chat.usage_sampler.sample(); + } yumush.update_waves(levels, cx); true }); @@ -3069,7 +3098,11 @@ fn stats_button(entity: &Entity, palette: Palette, open: bool) -> impl I cx.notify(); }), ) - .tip(if open { "Hide stats" } else { "Stats" }) + .tip(if open { + "Hide connection stats" + } else { + "Connection stats" + }) .size(px(26.)) .flex() .items_center() diff --git a/crates/client/src/gui/dock.rs b/crates/client/src/gui/dock.rs index a680e56..03b53ec 100644 --- a/crates/client/src/gui/dock.rs +++ b/crates/client/src/gui/dock.rs @@ -5,13 +5,13 @@ use common::{ share::Kind, }; use gpui_kit::{ - App, Div, Entity, FontWeight, Hsla, IntoElement, ParentElement, Stateful, Styled, Window, - assets::IconName, component::Icon, div, px, + App, Div, Entity, FontWeight, Hsla, InteractiveElement, IntoElement, ParentElement, Stateful, + StatefulInteractiveElement, Styled, Window, assets::IconName, component::Icon, div, px, }; use super::{ Palette, Tooltip as _, Yumush, chat::VoiceState, clickable, community_name, entity_action, - share_view::kind_icon, text, voice_stats, wave, widget::icon_button, + hoverable_with, share_view::kind_icon, text, voice_stats, wave, widget::icon_button, }; const PING_BARS: usize = 12; @@ -89,7 +89,7 @@ impl Yumush { .gap(px(7.)) .child( clickable("dock_go", palette, go) - .tip("Go to call") + .tip("Go to channel") .min_w_0() .truncate() .text_size(text(12.)) @@ -106,6 +106,8 @@ impl Yumush { .child(div().flex_1()) .child( div() + .id("dock_ping") + .tip("Ping") .flex_shrink_0() .h(px(22.)) .px(px(7.)) @@ -134,7 +136,8 @@ impl Yumush { }), ) .bg(palette.danger.opacity(0.13)) - .text_color(palette.danger), + .text_color(palette.danger) + .hover(|style| style.bg(palette.danger.opacity(0.22))), ) } @@ -151,8 +154,8 @@ impl Yumush { } else { palette.ok }; - let mic_entity = entity.clone(); let deafen_entity = entity.clone(); + let mic_action = entity_action(entity, |yumush, window, cx| yumush.toggle_mute(window, cx)); let ghost = self.hidden_in_voice(); let mic_icon = if muted { IconName::MicOff @@ -169,36 +172,38 @@ impl Yumush { } else { IconName::Headphones }; - let (deafen_bg, deafen_tone) = if deafened { - (palette.danger.opacity(0.13), palette.danger) + let (deafen_bg, deafen_tone, deafen_hover) = if deafened { + ( + palette.danger.opacity(0.13), + palette.danger, + palette.danger.opacity(0.22), + ) } else { - (palette.hover, palette.text) + (palette.hover, palette.text, palette.hover) }; - let mic = icon_button( - format!("dock_mic_{muted}_{ghost}"), - palette, - mic_icon, - mic_tip, - move |window, cx| mic_entity.update(cx, |yumush, cx| yumush.toggle_mute(window, cx)), - ) - .text_color(tone); let voice = div() .flex_1() .flex() .justify_center() .child(wave::wave_slot(self.chat.waves.voice(me), 14., tone)); - let group = div() - .flex_1() - .h(px(30.)) - .px(px(8.)) - .rounded(px(7.)) - .bg(tone.opacity(0.12)) - .flex() - .items_center() - .gap(px(4.)) - .child(mic) - .child(voice); + let group = hoverable_with( + "dock_mic", + div() + .flex_1() + .h(px(30.)) + .px(px(8.)) + .rounded(px(7.)) + .bg(tone.opacity(0.12)) + .flex() + .items_center() + .gap(px(4.)), + tone.opacity(0.2), + ) + .tip(mic_tip) + .on_click(move |_, window, cx| mic_action(window, cx)) + .child(Icon::new(mic_icon).w(px(14.)).h(px(14.)).text_color(tone)) + .child(voice); let deafen = icon_button( format!("dock_deafen_{deafened}"), palette, @@ -210,7 +215,8 @@ impl Yumush { .h(px(30.)) .rounded(px(7.)) .bg(deafen_bg) - .text_color(deafen_tone); + .text_color(deafen_tone) + .hover(move |style| style.bg(deafen_hover)); div() .flex() @@ -230,23 +236,26 @@ impl Yumush { .collect(); if !off.is_empty() { rows.push( - div().flex().items_center().gap(px(4.)).children( - off.into_iter() - .map(|kind| start_button(entity, kind, palette)), - ), + div() + .flex() + .items_center() + .gap(px(4.)) + .children(off.into_iter().map(|kind| { + div() + .flex_1() + .flex() + .items_center() + .gap(px(2.)) + .child(start_button(entity, kind, palette)) + .child(self.share_settings_button(entity, palette, kind)) + })), ); } - if let Some(last) = rows.pop() { - rows.push(last.child(self.share_settings_button(entity, palette, Kind::Screen))); - } div().flex().flex_col().gap(px(4.)).children(rows) } fn device_row(&self, entity: &Entity, me: Id, kind: Kind, palette: Palette) -> Div { - let tone = match kind { - Kind::Camera => palette.camera, - Kind::Screen => palette.screen, - }; + let tone = tone(palette, kind); let stop_tip = match kind { Kind::Camera => "Turn off camera", Kind::Screen => "Stop sharing", @@ -275,6 +284,8 @@ impl Yumush { if let Some(history) = self.chat.waves.share(me).filter(|_| kind == Kind::Screen) { row = row.child( div() + .id("dock_audio") + .tip("Screen audio") .h(px(20.)) .px(px(5.)) .rounded(px(5.)) @@ -291,35 +302,31 @@ impl Yumush { .child(wave::mini_wave(history, 10., tone)), ); } - row.child(div().flex_1()).child( - icon_button( - format!("dock_stop_{kind:?}"), - palette, - IconName::X, - stop_tip, - toggle_action(entity, kind), + row.child(div().flex_1()) + .child(self.share_settings_button(entity, palette, kind)) + .child( + icon_button( + format!("dock_stop_{kind:?}"), + palette, + IconName::X, + stop_tip, + toggle_action(entity, kind), + ) + .text_color(palette.danger), ) - .text_color(palette.danger), - ) } fn mode_text(&self, kind: Kind) -> String { - let best = self + let quality = self .chat .share_sample .sending .iter() .filter(|(sent, _)| *sent == kind) - .map(|(_, stats)| stats) - .max_by(|a, b| a.fps.total_cmp(&b.fps)); - match best { - Some(stats) => format!( - "{}p{}", - stats.layer.quality.resolution.height(), - stats.layer.quality.fps.value() - ), - None => "…".to_string(), - } + .map(|(_, stats)| stats.layer.quality) + .max_by_key(|quality| quality.resolution.height()) + .unwrap_or_else(|| self.settings.share.top(kind)); + format!("{}p{}", quality.resolution.height(), quality.fps.value()) } fn is_on(&self, kind: Kind) -> bool { @@ -342,6 +349,14 @@ fn start_button(entity: &Entity, kind: Kind, palette: Palette) -> Statef .h(px(30.)) .rounded(px(7.)) .bg(palette.hover) + .hover(move |style| style.bg(tone(palette, kind).opacity(0.2))) +} + +fn tone(palette: Palette, kind: Kind) -> Hsla { + match kind { + Kind::Camera => palette.camera, + Kind::Screen => palette.screen, + } } fn toggle_action(entity: &Entity, kind: Kind) -> impl Fn(&mut Window, &mut App) + 'static { diff --git a/crates/client/src/gui/share_view.rs b/crates/client/src/gui/share_view.rs index eb96127..36eb729 100644 --- a/crates/client/src/gui/share_view.rs +++ b/crates/client/src/gui/share_view.rs @@ -1,5 +1,8 @@ use common::model::Id; -use std::{sync::Arc, time::Duration}; +use std::{ + sync::Arc, + time::{Duration, Instant}, +}; use common::share::{Codec, Fps, Kind, Quality, Resolution, Source, options}; @@ -31,6 +34,7 @@ use super::{ media_view::into_render_image, notify_error, pop_in, settings_page::segmented, + stream_stats::{quality_label, stream_card, watch_stats}, surface::Surface, text, widget::{icon_button, spawn_warn}, @@ -44,6 +48,8 @@ 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"), @@ -93,6 +99,8 @@ pub(super) struct Viewer { pub(super) fullscreen: bool, volume: Entity, restore: f32, + active: Instant, + stats: bool, _subscriptions: Vec, _tick: Task<()>, } @@ -292,6 +300,8 @@ impl Yumush { fullscreen: false, volume, restore: FULL_VOLUME, + active: Instant::now(), + stats: false, _subscriptions: subscriptions, _tick: tick, }); @@ -478,31 +488,9 @@ impl Yumush { Kind::Screen => palette.screen, Kind::Camera => palette.camera, }; - let hud = self - .chat - .share_sample - .watching - .iter() - .find(|(user_id, kind, _)| *user_id == viewer.user_id && *kind == viewer.kind) - .map(|(_, _, stats)| { - let quality = stats.layer.as_ref().map_or("…".to_string(), |layer| { - format!( - "{}p{}", - layer.quality.resolution.height(), - layer.quality.fps.value() - ) - }); - let loss = if stats.loss * 100. > 0.5 { - format!(" · {:.1}% loss", stats.loss * 100.) - } else { - String::new() - }; - format!( - "{quality} · {} · {:.0} fps{loss}", - super::voice_stats::rate(stats.kbps), - stats.fps - ) - }); + let (user_id, kind) = (viewer.user_id, viewer.kind); + let stats = watch_stats(self, user_id, kind); + let bar = viewer.active.elapsed() < BAR_TTL; div() .flex_1() @@ -510,7 +498,20 @@ impl Yumush { .relative() .occlude() .bg(gpui_kit::black()) - .group("viewer") + .on_mouse_move({ + let entity = entity.clone(); + move |_, _, cx| { + entity.update(cx, |yumush, cx| { + if let Some(viewer) = yumush.chat.viewer.as_mut() { + let hidden = viewer.active.elapsed() >= BAR_TTL; + viewer.active = Instant::now(); + if hidden { + cx.notify(); + } + } + }) + } + }) .child( div() .id("viewer_video") @@ -527,21 +528,63 @@ impl Yumush { .left(px(10.)) .top(px(10.)), ) - .children(hud.map(|hud| { + .children(stats.map(|stats| { + let entity = entity.clone(); div() + .occlude() .absolute() .right(px(10.)) .top(px(10.)) - .h(px(24.)) - .px(px(8.)) .flex() .items_center() - .rounded(px(12.)) - .bg(gpui_kit::black().opacity(0.72)) - .text_size(text(11.)) - .text_color(tone) - .child(hud) + .gap(px(6.)) + .child( + div() + .h(px(22.)) + .px(px(8.)) + .flex() + .items_center() + .rounded(px(11.)) + .bg(gpui_kit::black().opacity(0.72)) + .text_size(text(11.)) + .text_color(tone) + .child(quality_label(stats)), + ) + .child( + div() + .id("viewer_stats_button") + .tip("Stream stats") + .size(px(26.)) + .flex() + .flex_shrink_0() + .items_center() + .justify_center() + .rounded(px(6.)) + .cursor_pointer() + .bg(gpui_kit::black().opacity(0.72)) + .text_color(if viewer.stats { tone } else { palette.muted }) + .hover(|style| style.bg(palette.hover).text_color(palette.text)) + .on_click(move |_, _, cx| { + entity.update(cx, |yumush, cx| { + if let Some(viewer) = yumush.chat.viewer.as_mut() { + viewer.stats = !viewer.stats; + } + cx.notify(); + }) + }) + .child(Icon::new(IconName::ChartBar).w(px(14.)).h(px(14.))), + ) })) + .when(viewer.stats, |this| { + this.child( + div() + .occlude() + .absolute() + .right(px(10.)) + .top(px(42.)) + .child(stream_card(self, user_id, kind, palette)), + ) + }) .child( div() .absolute() @@ -551,8 +594,7 @@ impl Yumush { .flex() .justify_center() .on_mouse_up(MouseButton::Left, |_, _, cx| cx.stop_propagation()) - .opacity(0.) - .group_hover("viewer", |style| style.opacity(1.)) + .when(!bar, |this| this.opacity(0.)) .child( div() .h(px(38.)) diff --git a/crates/client/src/gui/sidebar.rs b/crates/client/src/gui/sidebar.rs index 5c7d48b..d97a4db 100644 --- a/crates/client/src/gui/sidebar.rs +++ b/crates/client/src/gui/sidebar.rs @@ -144,6 +144,8 @@ impl Yumush { let ids = self.chat.voice_ids(community_id); let wave = ids.iter().find_map(|id| self.chat.waves.voice(*id)); div() + .id(format!("voice_chip_{community_id}")) + .tip("In call") .h(px(18.)) .px(px(5.)) .flex() @@ -251,12 +253,22 @@ impl Yumush { entity, identity, ))) - .children(camera.then(|| watch_pill(entity, user_id, Kind::Camera, None, palette))) + .children(camera.then(|| { + watch_pill( + entity, + user_id, + Kind::Camera, + self.is_watching(user_id, Kind::Camera), + None, + palette, + ) + })) .children(screen.then(|| { watch_pill( entity, user_id, Kind::Screen, + self.is_watching(user_id, Kind::Screen), self.chat.waves.share(user_id), palette, ) @@ -849,6 +861,7 @@ fn watch_pill( entity: &Entity, user_id: Id, kind: Kind, + watching: bool, wave: Option<&VecDeque>, palette: Palette, ) -> impl IntoElement { @@ -856,6 +869,11 @@ fn watch_pill( Kind::Camera => (palette.camera, IconName::Video), Kind::Screen => (palette.screen, IconName::ScreenShare), }; + let tip = match (watching, kind) { + (true, _) => "Stop watching", + (false, Kind::Camera) => "Watch camera", + (false, Kind::Screen) => "Watch screen", + }; clickable( format!("voice_watch_{user_id}_{kind:?}"), palette, @@ -863,7 +881,7 @@ fn watch_pill( yumush.toggle_viewer(user_id, kind, window, cx) }), ) - .tip("Watch") + .tip(tip) .h(px(18.)) .px(px(5.)) .flex() diff --git a/crates/client/src/gui/stream_stats.rs b/crates/client/src/gui/stream_stats.rs index 8b13789..f77cd1b 100644 --- a/crates/client/src/gui/stream_stats.rs +++ b/crates/client/src/gui/stream_stats.rs @@ -1 +1,196 @@ +use common::{model::Id, share::Kind}; +use gpui_kit::{Div, FontWeight, Hsla, ParentElement, Styled, component::Icon, div, px}; +use super::{Palette, Yumush, share_view::kind_icon, text, voice_stats::rate}; +use crate::{media::decode::Engine, share::session::WatchStats}; + +const GRAPH_HEIGHT: f32 = 48.; +const AXIS_WIDTH: f32 = 34.; + +pub(super) fn watch_stats(yumush: &Yumush, user_id: Id, kind: Kind) -> Option<&WatchStats> { + yumush + .chat + .share_sample + .watching + .iter() + .find(|(id, sent, _)| *id == user_id && *sent == kind) + .map(|(_, _, stats)| stats) +} + +pub(super) fn quality_label(stats: &WatchStats) -> String { + stats.layer.as_ref().map_or("…".to_string(), |layer| { + format!("{}p{:.0}", layer.quality.resolution.height(), stats.fps) + }) +} + +pub(super) fn stream_card(yumush: &Yumush, user_id: Id, kind: Kind, palette: Palette) -> Div { + let (tone, noun) = match kind { + Kind::Screen => (palette.screen, "screen"), + Kind::Camera => (palette.camera, "camera"), + }; + let user = yumush + .chat + .author(user_id) + .map_or("Someone", |user| user.username.as_str()); + let stats = watch_stats(yumush, user_id, kind); + let losses: Vec = yumush + .chat + .share_loss + .get(&(user_id, kind)) + .into_iter() + .flatten() + .copied() + .collect(); + let value = |format: fn(&WatchStats) -> String| stats.map_or("…".to_string(), format); + + div() + .w(px(300.)) + .p(px(12.)) + .flex() + .flex_col() + .gap(px(12.)) + .text_size(text(12.)) + .rounded(px(10.)) + .border_1() + .border_color(palette.border) + .bg(palette.panel) + .child( + div() + .flex() + .items_center() + .gap(px(6.)) + .child( + Icon::new(kind_icon(kind)) + .w(px(14.)) + .h(px(14.)) + .flex_none() + .text_color(tone), + ) + .child( + div() + .font_weight(FontWeight::SEMIBOLD) + .child(format!("{user}'s {noun}")), + ), + ) + .child(graph(&losses, tone, palette)) + .child(section( + "Stream", + vec![ + row( + "Resolution", + value(|stats| { + stats.layer.as_ref().map_or("…".to_string(), |layer| { + format!("{}p", layer.quality.resolution.height()) + }) + }), + palette, + ), + row("FPS", value(|stats| format!("{:.0}", stats.fps)), palette), + row( + "Engine", + value(|stats| { + match stats.engine { + Some(Engine::Hardware) => "HW", + Some(Engine::Software) => "SW", + None => "…", + } + .to_string() + }), + palette, + ), + row("Bitrate", value(|stats| rate(stats.kbps)), palette), + ], + palette, + )) + .child(section( + "Network", + vec![ + row( + "Loss", + value(|stats| format!("{:.1} %", stats.loss * 100.)), + palette, + ), + row( + "Buffer", + value(|stats| format!("{} ms", stats.buffer_ms)), + palette, + ), + row( + "Latency", + value(|stats| { + stats + .latency_ms + .map_or("…".to_string(), |ms| format!("{ms} ms")) + }), + palette, + ), + row( + "Keyframes", + value(|stats| stats.keyframes.to_string()), + palette, + ), + row("NACKs", value(|stats| stats.nacks.to_string()), palette), + ], + palette, + )) +} + +fn graph(losses: &[f32], color: Hsla, palette: Palette) -> Div { + let top = losses.iter().fold(1_f32, |top, loss| top.max(loss * 100.)); + let levels: Vec = losses.iter().map(|loss| loss * 100. / top).collect(); + + div() + .flex() + .gap(px(6.)) + .h(px(GRAPH_HEIGHT)) + .child( + div() + .w(px(AXIS_WIDTH)) + .h_full() + .flex() + .flex_col() + .justify_between() + .text_size(text(10.)) + .text_color(palette.muted) + .children([top, top / 2., 0.].map(|value| div().child(format!("{value:.1}%")))), + ) + .child( + div() + .flex_1() + .h_full() + .rounded(px(4.)) + .bg(palette.window) + .child(super::wave::line(levels, color)), + ) +} + +fn section(title: &'static str, rows: Vec
, palette: Palette) -> Div { + div() + .flex() + .flex_col() + .gap(px(4.)) + .child( + div() + .text_size(text(11.)) + .font_weight(FontWeight::SEMIBOLD) + .text_color(palette.muted) + .child(title), + ) + .children(rows) +} + +fn row(key: &'static str, value: String, palette: Palette) -> Div { + div() + .flex() + .items_center() + .justify_between() + .gap(px(8.)) + .text_size(text(11.)) + .child(div().text_color(palette.muted).child(key)) + .child( + div() + .font_family(super::MONO_FONT) + .text_color(palette.text) + .child(value), + ) +} diff --git a/crates/client/src/gui/voice_stats.rs b/crates/client/src/gui/voice_stats.rs index c861d8f..328bc36 100644 --- a/crates/client/src/gui/voice_stats.rs +++ b/crates/client/src/gui/voice_stats.rs @@ -6,18 +6,19 @@ use common::{ }; use gpui_kit::{ Div, FontWeight, Hsla, ParentElement, Styled, assets::IconName, component::Icon, div, hsla, - prelude::FluentBuilder as _, px, + prelude::FluentBuilder as _, px, relative, rgb, }; -use super::{Palette, chat::Chat, share_view::kind_icon, text}; +use super::{Palette, chat::Chat, share_view::kind_icon, text, wave}; use crate::media::decode::Engine; use crate::share::session::{LayerStats, WatchStats}; +use crate::usage::{Gpu, Usage}; use crate::voice::VoiceSample; pub const SAMPLE_HISTORY: usize = 60; const GRAPH_HEIGHT: f32 = 32.; +const MIRROR_HALF: f32 = 22.; const PING_SCALE: f32 = 150.; -const LOSS_SCALE: f32 = 10.; const GOOD_LOSS: f32 = 2.; const FAIR_LOSS: f32 = 8.; @@ -51,6 +52,14 @@ impl Quality { } } + fn word(self) -> &'static str { + match self { + Self::Good => "good", + Self::Fair => "fair", + Self::Poor => "poor", + } + } + pub fn color(self, palette: Palette) -> Hsla { match self { Self::Good => palette.ok, @@ -69,61 +78,128 @@ pub fn stats_panel(chat: &Chat, palette: Palette) -> Div { div() .flex() .flex_col() - .gap(px(10.)) + .gap(px(16.)) .child(network_block(chat, palette)) .children(sending_blocks(&share.sending, palette)) - .children( - share.watching.iter().map(|(user_id, kind, stats)| { - watching_block(*user_id, *kind, stats, chat, palette) - }), - ) + .child(receiving_block(&share.watching, chat, palette)) + .children(chat.usage.map(|usage| usage_block(usage, palette))) } fn network_block(chat: &Chat, palette: Palette) -> Div { let latest = chat.voice_samples.back(); - let value = |format: fn(&VoiceSample) -> String| latest.map_or("…".to_string(), format); let color = latest.map_or(palette.ok, |sample| Quality::of(sample).color(palette)); - block( - color, - IconName::Activity, - "Network", - value(|sample| format!("{:.0} ms", sample.ping_ms)), - ) - .child(graph( - "Ping", - chat.voice_samples - .iter() - .map(|sample| { - ( - sample.ping_ms / PING_SCALE, - Quality::of(sample).color(palette), + let word = latest.map_or("…", |sample| Quality::of(sample).word()); + let ping = latest.map_or("…".into(), |sample| format!("{:.0} ms", sample.ping_ms)); + let jitter = latest.map_or("…".into(), |sample| { + format!("{:.0} ms", sample.traffic.jitter_ms) + }); + let loss = latest.map_or("…".into(), |sample| { + format!("{:.1} %", sample.traffic.loss * 100.) + }); + let buffer = latest.map_or("…".into(), |sample| { + format!("{:.0} ms", sample.traffic.buffer_ms) + }); + + div() + .flex() + .flex_col() + .gap(px(8.)) + .child(header(IconName::Activity, "Network", color).child(chip(word, color))) + .child( + div() + .flex() + .gap(px(8.)) + .child(stat_cell("ping", ping, color, palette)) + .child(stat_cell("jitter", jitter, color, palette)) + .child(stat_cell("loss", loss, color, palette)) + .child(stat_cell("buffer", buffer, palette.text, palette)), + ) + .child( + div() + .h(px(GRAPH_HEIGHT)) + .p(px(2.)) + .rounded(px(4.)) + .bg(palette.window) + .child(wave::line( + chat.voice_samples + .iter() + .map(|sample| (sample.ping_ms / PING_SCALE).clamp(0., 1.)) + .collect(), + color, + )), + ) + .child(traffic(chat, palette)) +} + +fn traffic(chat: &Chat, palette: Palette) -> Div { + let up: Vec = chat.traffic.iter().map(|(up, _)| *up).collect(); + let down: Vec = chat.traffic.iter().map(|(_, down)| *down).collect(); + let up_latest = up.last().copied().unwrap_or_default(); + let down_latest = down.last().copied().unwrap_or_default(); + let max = up.iter().chain(&down).copied().fold(1., f32::max); + + div() + .flex() + .flex_col() + .gap(px(2.)) + .text_size(text(10.)) + .child( + div() + .text_color(up_color()) + .child(format!("↑ {}", rate(up_latest as u32))), + ) + .child( + div() + .h(px(MIRROR_HALF * 2.)) + .flex() + .flex_col() + .child( + div() + .h(px(MIRROR_HALF)) + .flex() + .items_end() + .gap(px(1.)) + .children(bars(&up, max, up_color())), ) - }) - .collect(), - palette, - )) - .child(row( - "Jitter", - value(|sample| format!("{:.0} ms", sample.traffic.jitter_ms)), - palette.text, - palette, - )) - .child(row( - "Loss", - value(|sample| format!("{:.1} %", sample.traffic.loss * 100.)), - palette.text, - palette, - )) - .child(row( - "Bitrate", - value(|sample| format!("{} kbps", sample.bitrate_kbps)), - palette.text, - palette, - )) + .child(div().h(px(1.)).bg(palette.border)) + .child( + div() + .h(px(MIRROR_HALF)) + .flex() + .items_start() + .gap(px(1.)) + .children(bars(&down, max, down_color())), + ), + ) + .child( + div() + .text_color(down_color()) + .child(format!("↓ {}", rate(down_latest as u32))), + ) +} + +fn bars(values: &[f32], max: f32, color: Hsla) -> Vec
{ + let empty = SAMPLE_HISTORY.saturating_sub(values.len()); + (0..empty) + .map(|_| div().flex_1()) + .chain( + values + .iter() + .map(|value| div().flex_1().h(px(value / max * MIRROR_HALF)).bg(color)), + ) + .collect() +} + +fn up_color() -> Hsla { + rgb(0xa78bfa).into() +} + +fn down_color() -> Hsla { + rgb(0x22d3ee).into() } fn sending_blocks(sending: &[(Kind, LayerStats)], palette: Palette) -> Vec
{ - [Kind::Camera, Kind::Screen] + [Kind::Screen, Kind::Camera] .into_iter() .filter_map(|kind| { let layers: Vec<&LayerStats> = sending @@ -137,79 +213,223 @@ fn sending_blocks(sending: &[(Kind, LayerStats)], palette: Palette) -> Vec
} fn sending_block(kind: Kind, layers: &[&LayerStats], palette: Palette) -> Div { - let total: u32 = layers.iter().map(|stats| stats.kbps).sum(); - let mut panel = block( - kind_color(kind, palette), - kind_icon(kind), - format!("{kind:?}"), - rate(total), - ); - for stats in layers { - panel = panel.child(row( - layer_text(stats.layer, stats.engine), - format!("{:.0} fps · {}", stats.fps, rate(stats.kbps)), - palette.text, - palette, - )); - } - panel + let color = kind_color(kind, palette); + let max = largest(layers.iter().map(|stats| stats.kbps)); + let engine = layers + .last() + .map_or("…", |stats| engine_label(stats.engine)); + div() + .flex() + .flex_col() + .gap(px(6.)) + .child(header(kind_icon(kind), kind_name(kind), color).child(label(engine, color))) + .children( + layers + .iter() + .enumerate() + .rev() + .map(|(index, stats)| layer_row(index, stats, max, kind, palette)), + ) } -fn watching_block( - user_id: Id, - kind: Kind, - stats: &WatchStats, - chat: &Chat, - palette: Palette, -) -> Div { +fn layer_row(index: usize, stats: &LayerStats, max: f32, kind: Kind, palette: Palette) -> Div { + let color = kind_color(kind, palette); + div() + .flex() + .items_center() + .gap(px(8.)) + .h(px(28.)) + .px(px(8.)) + .rounded(px(7.)) + .bg(color.opacity(0.08)) + .text_size(text(11.)) + .when(stats.kbps == 0, |this| this.opacity(0.45)) + .child( + div() + .w(px(22.)) + .flex_none() + .font_weight(FontWeight::SEMIBOLD) + .text_color(color) + .child(format!("L{index}")), + ) + .child( + div() + .w(px(70.)) + .flex_none() + .text_color(palette.text) + .child(resolution_text(stats.layer, stats.fps)), + ) + .child(bar(stats.kbps as f32 / max, color, palette)) + .child( + div() + .w(px(52.)) + .flex_none() + .text_right() + .text_color(palette.text) + .child(rate(stats.kbps)), + ) +} + +fn receiving_block(watching: &[(Id, Kind, WatchStats)], chat: &Chat, palette: Palette) -> Div { + div() + .flex() + .flex_col() + .gap(px(6.)) + .child(header(IconName::Eye, "Receiving", palette.text)) + .children( + watching + .iter() + .map(|(user_id, kind, stats)| watch_row(chat, *user_id, *kind, stats, palette)), + ) +} + +fn watch_row(chat: &Chat, user_id: Id, kind: Kind, stats: &WatchStats, palette: Palette) -> Div { let name = chat .author(user_id) .map_or_else(|| user_id.to_string(), |user| user.username.clone()); + let color = palette.tinted(user_id); let loss = stats.loss * 100.; - let losses = chat - .share_loss - .get(&(user_id, kind)) - .into_iter() - .flatten() - .map(|loss| { - ( - loss * 100. / LOSS_SCALE, - Quality::of_loss(loss * 100.).color(palette), - ) - }) - .collect(); - block( - kind_color(kind, palette), - kind_icon(kind), - name, - rate(stats.kbps), - ) - .child(row("Layer", watch_layer_text(stats), palette.text, palette)) - .child(row( - "FPS", - format!("{:.0}", stats.fps), - palette.text, - palette, - )) - .child(row( - "Loss", - format!("{loss:.1} %"), - Quality::of_loss(loss).color(palette), - palette, - )) - .child(row( - "Buffer", - format!("{} ms", stats.buffer_ms), - palette.text, - palette, - )) - .child(row( - "Keyframes", - stats.keyframes.to_string(), - palette.text, + let loss_color = Quality::of_loss(loss).color(palette); + let latency = stats + .latency_ms + .map_or("…".to_string(), |ms| format!("{ms} ms")); + div() + .flex() + .items_center() + .gap(px(4.)) + .h(px(30.)) + .px(px(6.)) + .rounded(px(7.)) + .bg(kind_color(kind, palette).opacity(0.06)) + .text_size(text(11.)) + .child(avatar_dot(&name, color)) + .child( + div() + .flex_1() + .min_w_0() + .truncate() + .font_weight(FontWeight::SEMIBOLD) + .text_color(color) + .child(name), + ) + .child( + Icon::new(kind_icon(kind)) + .w(px(11.)) + .h(px(11.)) + .flex_none() + .text_color(kind_color(kind, palette)), + ) + .child( + div().w(px(64.)).flex_none().text_color(palette.text).child( + stats + .layer + .map_or("…".to_string(), |layer| resolution_text(layer, stats.fps)), + ), + ) + .child( + div() + .w(px(20.)) + .flex_none() + .text_color(palette.muted) + .child(stats.engine.map_or("…", engine_label)), + ) + .child( + div() + .w(px(44.)) + .flex_none() + .text_right() + .text_color(palette.text) + .child(rate(stats.kbps)), + ) + .child( + div() + .w(px(52.)) + .flex_none() + .text_right() + .text_color(palette.muted) + .child(latency), + ) + .child(chip(format!("{loss:.1}%"), loss_color)) +} + +fn usage_block(usage: Usage, palette: Palette) -> Div { + let cpu = div() + .flex() + .flex_col() + .gap(px(6.)) + .flex_1() + .min_w_0() + .child(header(IconName::Cpu, "CPU", palette.text)) + .child(meter("total", usage.total, palette.text, palette)) + .child(meter("gui", usage.gui, palette.accent, palette)) + .child(meter("camera", usage.camera, palette.camera, palette)) + .child(meter("encode", usage.encode, palette.screen, palette)) + .child(meter("decode", usage.decode, palette.ok, palette)); + div() + .flex() + .gap(px(20.)) + .child(cpu) + .children(usage.gpu.map(|gpu| gpu_column(gpu, palette))) +} + +fn gpu_column(gpu: Gpu, palette: Palette) -> Div { + div() + .flex() + .flex_col() + .gap(px(6.)) + .flex_1() + .min_w_0() + .child(header(IconName::MemoryStick, "GPU", palette.text)) + .child(meter("3d", gpu.gfx, palette.accent, palette)) + .child(meter("encode", gpu.encode, palette.screen, palette)) + .child(meter("decode", gpu.decode, palette.ok, palette)) + .child(meter_value( + "vram", + format!("{} MB", gpu.vram_mb), + 0., + palette.muted, + palette, + )) +} + +fn meter(label: &'static str, percent: f32, color: Hsla, palette: Palette) -> Div { + meter_value( + label, + format!("{percent:.1} %"), + percent / 100., + color, palette, - )) - .child(graph("Loss", losses, palette)) + ) +} + +fn meter_value( + label: &'static str, + value: String, + fraction: f32, + color: Hsla, + palette: Palette, +) -> Div { + div() + .flex() + .items_center() + .gap(px(6.)) + .text_size(text(11.)) + .child( + div() + .w(px(46.)) + .flex_none() + .text_color(palette.muted) + .child(label), + ) + .child(bar(fraction, color, palette)) + .child( + div() + .w(px(56.)) + .flex_none() + .text_right() + .text_color(palette.text) + .child(value), + ) } fn kind_color(kind: Kind, palette: Palette) -> Hsla { @@ -219,6 +439,17 @@ fn kind_color(kind: Kind, palette: Palette) -> Hsla { } } +fn kind_name(kind: Kind) -> &'static str { + match kind { + Kind::Camera => "Camera", + Kind::Screen => "Screen", + } +} + +fn largest(values: impl Iterator) -> f32 { + values.max().unwrap_or(0).max(1) as f32 +} + pub fn rate(kbps: u32) -> String { match kbps { 0..1000 => format!("{kbps} kb"), @@ -226,113 +457,106 @@ pub fn rate(kbps: u32) -> String { } } -fn layer_text(layer: Layer, engine: Engine) -> String { +fn engine_label(engine: Engine) -> &'static str { + match engine { + Engine::Hardware => "HW", + Engine::Software => "SW", + } +} + +fn resolution_text(layer: Layer, fps: f32) -> String { format!( - "{}p{} · {}", + "{}p{}", layer.quality.resolution.height(), - layer.quality.fps.value(), - match engine { - Engine::Hardware => "HW", - Engine::Software => "SW", - } + fps.round() as u32 ) } -fn watch_layer_text(stats: &WatchStats) -> String { - match (stats.layer, stats.engine) { - (Some(layer), Some(engine)) => layer_text(layer, engine), - _ => "…".to_string(), - } -} - -fn block( - color: Hsla, - icon: IconName, - title: impl gpui_kit::IntoElement, - summary: impl gpui_kit::IntoElement, -) -> Div { +fn header(icon: IconName, title: &'static str, color: Hsla) -> Div { div() - .rounded(px(10.)) - .p(px(8.)) - .bg(color.opacity(0.07)) .flex() - .flex_col() - .gap(px(4.)) + .items_center() + .gap(px(7.)) + .child( + Icon::new(icon) + .w(px(13.)) + .h(px(13.)) + .flex_none() + .text_color(color), + ) .child( div() - .flex() - .items_center() - .gap(px(6.)) - .child( - Icon::new(icon) - .w(px(14.)) - .h(px(14.)) - .flex_none() - .text_color(color), - ) - .child( - div() - .flex_1() - .font_weight(FontWeight::SEMIBOLD) - .text_size(text(12.)) - .text_color(color) - .child(title), - ) - .child( - div() - .flex_none() - .text_size(text(11.)) - .text_color(color) - .child(summary), - ), + .font_weight(FontWeight::SEMIBOLD) + .text_size(text(12.)) + .text_color(color) + .child(title), ) + .child(div().flex_1()) } -fn row( - label: impl gpui_kit::IntoElement, - value: impl gpui_kit::IntoElement, - value_color: Hsla, - palette: Palette, -) -> Div { - div() - .flex() - .items_center() - .justify_between() - .gap(px(6.)) - .text_size(text(11.)) - .child(div().text_color(palette.muted).child(label)) - .child(div().text_color(value_color).child(value)) +fn label(value: &'static str, color: Hsla) -> Div { + div().text_size(text(11.)).text_color(color).child(value) } -fn graph(label: &'static str, bars: Vec<(f32, Hsla)>, palette: Palette) -> Div { - let empty = SAMPLE_HISTORY.saturating_sub(bars.len()); - let empty_bars = bars.is_empty(); - let bars = bars.into_iter().map(|(level, color)| { - let height = level.clamp(0.04, 1.) * GRAPH_HEIGHT; - div().flex_1().h(px(height)).rounded_t(px(1.)).bg(color) - }); +fn chip(value: impl gpui_kit::IntoElement, color: Hsla) -> Div { + div() + .flex_none() + .px(px(6.)) + .py(px(1.)) + .rounded(px(5.)) + .bg(color.opacity(0.13)) + .text_size(text(10.)) + .text_color(color) + .child(value) +} +fn stat_cell(label: &'static str, value: String, color: Hsla, palette: Palette) -> Div { div() + .flex_1() + .min_w_0() .flex() .flex_col() - .gap(px(4.)) + .gap(px(2.)) .child( div() .text_size(text(10.)) .text_color(palette.muted) .child(label), ) + .child(div().text_size(text(14.)).text_color(color).child(value)) +} + +fn avatar_dot(name: &str, color: Hsla) -> Div { + let initial = name + .chars() + .next() + .map_or('?', |letter| letter.to_ascii_uppercase()); + div() + .size(px(18.)) + .flex_none() + .rounded_full() + .flex() + .items_center() + .justify_center() + .bg(color) + .text_size(text(9.)) + .font_weight(FontWeight::BOLD) + .text_color(hsla(0., 0., 0.07, 1.)) + .child(initial.to_string()) +} + +fn bar(fraction: f32, color: Hsla, palette: Palette) -> Div { + div() + .flex_1() + .min_w_0() + .h(px(4.)) + .rounded_full() + .bg(palette.border) .child( div() - .h(px(GRAPH_HEIGHT)) - .p(px(2.)) - .flex() - .items_end() - .gap(px(1.)) - .rounded(px(4.)) - .bg(palette.window) - .children((0..empty).map(|_| div().flex_1())) - .children(bars) - .when(empty_bars, |this| this.opacity(0.5)), + .h_full() + .w(relative(fraction.clamp(0., 1.))) + .rounded_full() + .bg(color), ) } diff --git a/crates/client/src/gui/wave.rs b/crates/client/src/gui/wave.rs index 359b4b6..8b2f904 100644 --- a/crates/client/src/gui/wave.rs +++ b/crates/client/src/gui/wave.rs @@ -1,7 +1,11 @@ use std::collections::{HashMap, HashSet, VecDeque}; use common::model::Id; -use gpui_kit::{Div, Hsla, ParentElement, Styled, div, px}; +use gpui_kit::{ + Div, Hsla, IntoElement, ParentElement, PathBuilder, Styled, canvas, div, point, px, +}; + +use super::voice_stats::SAMPLE_HISTORY; use crate::net::Levels; @@ -137,3 +141,27 @@ fn wave(bars: &[f32], size: f32, color: Hsla) -> Div { .bg(color) })) } + +pub fn line(levels: Vec, color: Hsla) -> impl IntoElement { + canvas( + |_, _, _| {}, + move |bounds, _, window, _| { + let first = SAMPLE_HISTORY.saturating_sub(levels.len()); + let mut path = PathBuilder::stroke(px(1.5)); + for (index, &level) in levels.iter().enumerate() { + let step = (first + index) as f32 / (SAMPLE_HISTORY - 1) as f32; + let x = bounds.origin.x + bounds.size.width * step; + let y = bounds.origin.y + bounds.size.height * (1. - level); + if index == 0 { + path.move_to(point(x, y)); + } else { + path.line_to(point(x, y)); + } + } + if let Ok(path) = path.build() { + window.paint_path(path, color); + } + }, + ) + .size_full() +} diff --git a/crates/client/src/usage.rs b/crates/client/src/usage.rs index 8b13789..0b44416 100644 --- a/crates/client/src/usage.rs +++ b/crates/client/src/usage.rs @@ -1 +1,198 @@ +#[derive(Clone, Copy, Default)] +pub struct Usage { + pub total: f32, + pub gui: f32, + pub camera: f32, + pub encode: f32, + pub decode: f32, + pub gpu: Option, +} +#[derive(Clone, Copy, Default)] +pub struct Gpu { + pub gfx: f32, + pub encode: f32, + pub decode: f32, + pub vram_mb: u32, +} + +#[cfg(target_os = "linux")] +pub use linux::Sampler; + +#[cfg(not(target_os = "linux"))] +#[derive(Default)] +pub struct Sampler; + +#[cfg(not(target_os = "linux"))] +impl Sampler { + pub fn sample(&mut self) -> Option { + None + } +} + +#[cfg(target_os = "linux")] +mod linux { + use std::{collections::HashMap, fs, time::Instant}; + + use super::{Gpu, Usage}; + + #[derive(Clone, Copy, Default)] + struct Ticks { + total: u64, + gui: u64, + camera: u64, + encode: u64, + decode: u64, + } + + #[derive(Clone, Copy, Default)] + struct Engines { + gfx: u64, + encode: u64, + decode: u64, + vram_kib: u64, + } + + #[derive(Clone, Copy)] + struct Snapshot { + at: Instant, + ticks: Ticks, + gpu: Option, + } + + #[derive(Default)] + pub struct Sampler { + previous: Option, + } + + impl Sampler { + pub fn sample(&mut self) -> Option { + let current = Snapshot::read()?; + let previous = self.previous.replace(current)?; + let wall = current.at.duration_since(previous.at); + let seconds = wall.as_secs_f32().max(f32::EPSILON); + let nanos = (wall.as_nanos() as f32).max(1.); + let cpu = |now: u64, before: u64| now.saturating_sub(before) as f32 / seconds; + let (now, then) = (current.ticks, previous.ticks); + Some(Usage { + total: cpu(now.total, then.total), + gui: cpu(now.gui, then.gui), + camera: cpu(now.camera, then.camera), + encode: cpu(now.encode, then.encode), + decode: cpu(now.decode, then.decode), + gpu: current.gpu.map(|gpu| { + let before = previous.gpu.unwrap_or(gpu); + let share = + |now: u64, then: u64| now.saturating_sub(then) as f32 / nanos * 100.; + Gpu { + gfx: share(gpu.gfx, before.gfx), + encode: share(gpu.encode, before.encode), + decode: share(gpu.decode, before.decode), + vram_mb: (gpu.vram_kib / 1024) as u32, + } + }), + }) + } + } + + impl Snapshot { + fn read() -> Option { + let ticks = Ticks::read()?; + Some(Self { + at: Instant::now(), + ticks, + gpu: read_gpu(), + }) + } + } + + impl Ticks { + fn read() -> Option { + let pid = std::process::id().to_string(); + let mut ticks = Self { + total: stat_ticks(&fs::read_to_string("/proc/self/stat").ok()?)?, + ..Self::default() + }; + for entry in fs::read_dir("/proc/self/task").ok()?.flatten() { + let path = entry.path(); + let Ok(name) = fs::read_to_string(path.join("comm")) else { + continue; + }; + let Some(used) = fs::read_to_string(path.join("stat")) + .ok() + .and_then(|stat| stat_ticks(&stat)) + else { + continue; + }; + let main = entry.file_name().to_str() == Some(pid.as_str()); + let name = name.trim(); + if main { + ticks.gui += used; + } else if name.starts_with("camera") || name.starts_with("share-capture") { + ticks.camera += used; + } else if name == "share-encode" { + ticks.encode += used; + } else if name == "media-decode" || name.contains("video") { + ticks.decode += used; + } + } + Some(ticks) + } + } + + fn stat_ticks(stat: &str) -> Option { + let rest = stat.get(stat.rfind(')')? + 1..)?; + let fields: Vec<&str> = rest.split_whitespace().collect(); + let utime: u64 = fields.get(11)?.parse().ok()?; + let stime: u64 = fields.get(12)?.parse().ok()?; + Some(utime + stime) + } + + fn read_gpu() -> Option { + let mut clients: HashMap = HashMap::new(); + for entry in fs::read_dir("/proc/self/fdinfo").ok()?.flatten() { + let Ok(info) = fs::read_to_string(entry.path()) else { + continue; + }; + let mut engines = Engines::default(); + let mut client = None; + let mut drm = false; + for line in info.lines().filter(|line| line.starts_with("drm-")) { + drm = true; + let Some((key, value)) = line.split_once(':') else { + continue; + }; + let Some(number) = value + .split_whitespace() + .next() + .and_then(|value| value.parse::().ok()) + else { + continue; + }; + match key { + "drm-client-id" => client = Some(number), + "drm-engine-gfx" => engines.gfx = number, + "drm-engine-enc" => engines.encode = number, + "drm-engine-dec" => engines.decode = number, + "drm-memory-vram" => engines.vram_kib = number, + _ => {} + } + } + if drm { + let key = + client.map_or_else(|| entry.path().display().to_string(), |id| id.to_string()); + clients.insert(key, engines); + } + } + (!clients.is_empty()).then(|| { + clients + .values() + .fold(Engines::default(), |sum, engines| Engines { + gfx: sum.gfx + engines.gfx, + encode: sum.encode + engines.encode, + decode: sum.decode + engines.decode, + vram_kib: sum.vram_kib + engines.vram_kib, + }) + }) + } +}