diff --git a/crates/client/Cargo.toml b/crates/client/Cargo.toml index 21af393..2dcef8d 100644 --- a/crates/client/Cargo.toml +++ b/crates/client/Cargo.toml @@ -21,6 +21,8 @@ ec-aac = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e844 ec-mp3 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" } ec-vorbis = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" } ec-flac = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" } +ec-h265 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" } +ec-vp9 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" } ureq = "3.5.2" bytes = "1.12.2" tracing = "0.1.44" @@ -34,6 +36,9 @@ rtrb = "0.4.1" [target.'cfg(target_os = "linux")'.dependencies] pipewire = { version = "0.10.1", features = ["v0_3_49"] } ksni = "0.3.7" +ashpd = { version = "0.14.3", default-features = false, features = ["tokio", "screencast"] } +ec-hw = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" } +ec-va = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" } [target.'cfg(target_os = "windows")'.dependencies] wasapi = "0.27.0" diff --git a/crates/client/src/gui.rs b/crates/client/src/gui.rs index 9c330c6..ae19651 100644 --- a/crates/client/src/gui.rs +++ b/crates/client/src/gui.rs @@ -52,6 +52,7 @@ mod message_actions; mod poll; mod profile; mod settings_page; +mod share_view; mod sidebar; mod snippet; mod social; @@ -601,6 +602,7 @@ pub struct Yumush { deferred: Vec, backups: Vec, pending_backup_delete: Option, + share_apps: Vec, } impl Yumush { @@ -612,6 +614,7 @@ impl Yumush { cx: &mut Context, ) -> Self { network.set_voice_settings(settings.voice.clone()); + network.set_share_settings(settings.share.clone()); cx.spawn(async move |this, cx| { while let Some(event) = network_event_receiver.recv().await { @@ -660,6 +663,7 @@ impl Yumush { deferred: Vec::new(), backups: Vec::new(), pending_backup_delete: None, + share_apps: Vec::new(), } } @@ -951,6 +955,9 @@ impl Yumush { user_id, muted: true, } if self.is_me(user_id) => self.set_muted(true, cx), + Event::ShareStopped { user_id, .. } if self.is_watching(user_id) => { + self.close_viewer(cx) + } Event::Typing { .. } => { cx.spawn(async move |this, cx| { cx.background_executor().timer(chat::TYPING_TTL).await; diff --git a/crates/client/src/gui/chat.rs b/crates/client/src/gui/chat.rs index 041813f..0f1dc5b 100644 --- a/crates/client/src/gui/chat.rs +++ b/crates/client/src/gui/chat.rs @@ -7,7 +7,8 @@ use std::{ }; use crate::gui::social::InviteLookup; -use crate::gui::voice_stats::SAMPLE_HISTORY; +use crate::gui::voice_stats::{SAMPLE_HISTORY, StatsTab}; +use crate::share::session::ShareSample; use crate::gui::{ FIND_HINT, Palette, Tooltip as _, Yumush, avatar, badge, builder::{BuilderTab, Transfer}, @@ -20,6 +21,7 @@ use crate::gui::{ primary_button, profile::profile_popover, rank_tag, + share_view::{self, Viewer}, sidebar::SidebarTab, snippet, voice_note::{self, VoiceNote}, @@ -34,6 +36,7 @@ use common::{ ServerBan, SessionInfo, Unread, Usage, User, VoiceRoom, mentions, }, permission, + share::Share, }; use gpui_kit::{ Anchor, AnyElement, App, AppContext, Context, Div, Entity, FontWeight, Image, @@ -230,9 +233,14 @@ pub struct Chat { pub(super) builder_voice_rooms: Vec, pub(super) voice_task: Option>, pub(super) voice_samples: VecDeque, + pub(super) share_sample: ShareSample, + pub(super) share_loss: HashMap>, + pub(super) stats_tab: StatsTab, pub(super) ringing: HashSet, pub(super) ring_task: Option>, pub(super) media: Media, + pub(super) shares: HashMap>, + pub(super) viewer: Option, pub(super) typing: HashMap>, pub(super) typing_sent: HashMap, } @@ -442,11 +450,16 @@ impl Chat { builder_voice_rooms: Vec::new(), voice_task: None, voice_samples: VecDeque::new(), + share_sample: ShareSample::default(), + share_loss: HashMap::new(), + stats_tab: StatsTab::Voice, ringing: HashSet::new(), ring_task: None, typing: HashMap::new(), typing_sent: HashMap::new(), media: Media::default(), + shares: HashMap::new(), + viewer: None, composer: Composer::Compose { reply: None }, } } @@ -588,6 +601,23 @@ impl Chat { .or_default() .insert(user_id, Instant::now()); } + Event::ShareStarted { + community_id, + share, + } => { + let shares = self.shares.entry(community_id).or_default(); + shares.retain(|existing| existing.user_id != share.user_id); + shares.push(share); + } + Event::ShareStopped { + community_id, + user_id, + } => { + if let Some(shares) = self.shares.get_mut(&community_id) { + shares.retain(|share| share.user_id != user_id); + } + } + Event::ShareLayers(_) | Event::KeyframeWanted(_) => {} Event::ReportCreated | Event::Announcement { .. } => {} } } @@ -1039,6 +1069,12 @@ impl Chat { .any(|community| community.id == community_id && community.voice_enabled) } + pub fn is_sharing(&self, community_id: &str, user_id: &str) -> bool { + self.shares + .get(community_id) + .is_some_and(|shares| shares.iter().any(|share| share.user_id == user_id)) + } + pub fn voice_ids(&self, community_id: &str) -> &[String] { self.voice .get(community_id) @@ -1051,6 +1087,21 @@ impl Chat { self.speaking.clear(); self.voice_task = None; self.voice_samples.clear(); + self.share_sample = ShareSample::default(); + self.share_loss.clear(); + } + + pub fn record_share(&mut self, sample: ShareSample) { + self.share_loss + .retain(|user_id, _| sample.watching.iter().any(|(id, _)| id == user_id)); + for (user_id, stats) in &sample.watching { + let history = self.share_loss.entry(user_id.clone()).or_default(); + history.push_back(stats.loss); + while history.len() > SAMPLE_HISTORY { + history.pop_front(); + } + } + self.share_sample = sample; } } @@ -1160,6 +1211,7 @@ impl Yumush { .size_full() .child(self.sidebar(&entity, &self.search_query(cx), palette)) .child(self.main_panel(&entity, palette, cx)) + .children(self.fullscreen_viewer(&entity, palette)) } fn main_panel(&self, entity: &Entity, palette: Palette, cx: &App) -> impl IntoElement { @@ -1191,8 +1243,12 @@ impl Yumush { .child(self.header(entity, themed)) .children(self.unread_bar(entity, themed)) .children(self.poll_banner(entity, themed)) - .child(self.message_area(entity, themed)) - .child(self.composer(entity, themed)), + .map(|panel| match self.inline_viewer(entity, themed) { + Some(viewer) => panel.child(viewer), + None => panel + .child(self.message_area(entity, themed)) + .child(self.composer(entity, themed)), + }), None => panel.child(empty_state(palette)), }, }) @@ -1504,6 +1560,7 @@ impl Yumush { self.load_members(window, cx); self.load_pins(window, cx); self.load_voice(window, cx); + self.load_shares(community_id, cx); self.load_messages(None, window, cx); cx.notify(); } @@ -1913,6 +1970,7 @@ impl Yumush { muted || yumush.is_server_muted() || yumush.hidden_in(&community_id); yumush.network.set_muted(muted); yumush.chat.voice.insert(community_id.clone(), participants); + yumush.load_shares(community_id.clone(), cx); yumush.chat.voice_state = VoiceState::In { community_id, muted, @@ -2086,12 +2144,12 @@ impl Yumush { .timer(Duration::from_millis(150)) .await; let speaking = network.speaking(); - let sample = (sampled.elapsed() >= VOICE_SAMPLE_INTERVAL) - .then(|| network.voice_sample()) - .flatten(); - if sample.is_some() { + let due = sampled.elapsed() >= VOICE_SAMPLE_INTERVAL; + if due { sampled = Instant::now(); } + let sample = due.then(|| network.voice_sample()).flatten(); + let share = due.then(|| network.share_sample()); let polling = this.update(cx, |yumush, cx| { if yumush.chat.voice_community().is_none() { return false; @@ -2104,6 +2162,10 @@ impl Yumush { } cx.notify(); } + if let Some(share) = share { + yumush.chat.record_share(share); + cx.notify(); + } yumush.update_speaking(speaking, cx); true }); @@ -2337,10 +2399,16 @@ impl Yumush { if users.is_empty() { return None; } + let sharers: Vec = users + .iter() + .filter(|user| self.chat.is_sharing(community_id, &user.id)) + .map(|user| user.id.clone()) + .collect(); Some( div() .flex() + .items_center() .children(users.into_iter().take(3).enumerate().map(|(index, user)| { let ring = if self.chat.speaking.contains(&user.id) { palette.ok @@ -2360,7 +2428,12 @@ impl Yumush { .hover(move |style| style.border_color(palette.accent)) .when(index > 0, |this| this.ml(px(-6.))), ) - })), + })) + .children( + sharers + .iter() + .map(|user_id| share_view::share_badge(entity, user_id, palette)), + ), ) } diff --git a/crates/client/src/gui/media_view.rs b/crates/client/src/gui/media_view.rs index ca68023..a0013c0 100644 --- a/crates/client/src/gui/media_view.rs +++ b/crates/client/src/gui/media_view.rs @@ -165,7 +165,7 @@ pub(super) async fn upload_file( uploaded } -fn to_render_image(frame: &crate::media::Frame) -> Option> { +pub(super) fn to_render_image(frame: &crate::media::Frame) -> Option> { let buffer = image::RgbaImage::from_raw(frame.width, frame.height, frame.bgra.to_vec())?; Some(Arc::new(RenderImage::new(vec![image::Frame::new(buffer)]))) } diff --git a/crates/client/src/gui/settings_page.rs b/crates/client/src/gui/settings_page.rs index 2041930..d01921d 100644 --- a/crates/client/src/gui/settings_page.rs +++ b/crates/client/src/gui/settings_page.rs @@ -614,14 +614,14 @@ pub(super) fn segment(item: E, active: bool, palette: Palette) -> E { .text_color(text) } -pub(super) fn segmented( - options: [(T, &'static str); N], +pub(super) fn segmented( + options: impl IntoIterator, selected: T, entity: &Entity, palette: Palette, select: fn(&mut Yumush, T, &mut Context), ) -> impl IntoElement { - segment_track(palette).children(options.map(|(choice, label)| { + segment_track(palette).children(options.into_iter().map(|(choice, label)| { let entity = entity.clone(); segment( diff --git a/crates/client/src/gui/share_view.rs b/crates/client/src/gui/share_view.rs new file mode 100644 index 0000000..9b9411c --- /dev/null +++ b/crates/client/src/gui/share_view.rs @@ -0,0 +1,762 @@ +use std::{sync::Arc, time::Duration}; + +use common::share::{Codec, Fps, Quality, Resolution}; +use gpui_kit::{ + Anchor, AnyElement, AppContext, Context, Div, Entity, FontWeight, InteractiveElement, + IntoElement, MouseButton, ObjectFit, ParentElement, RenderImage, Styled, StyledImage, + StatefulInteractiveElement, Subscription, Task, Window, + assets::IconName, + component::{ + Icon, + popover::Popover, + slider::{Slider, SliderEvent, SliderState}, + switch::Switch, + }, + div, img, px, +}; + +use super::{ + Palette, Tooltip as _, Trigger, Yumush, chat::View, clickable, entity_action, + media_view::to_render_image, notify_error, pop_in, settings_page::segmented, + sidebar::icon_button, text, +}; +use crate::{ + settings::{self, SHARE_QUALITY, ShareAudio, ShareCodec, ShareSettings}, + share::{ + audio_capture::{AudioApp, AudioKind}, + encode::capabilities, + session::WatchQuality, + }, +}; + +const FRAME_TICK: Duration = Duration::from_millis(16); +const RESOLUTIONS: [(Resolution, &str); 6] = [ + (Resolution::P360, "360"), + (Resolution::P480, "480"), + (Resolution::P720, "720"), + (Resolution::P1080, "1080"), + (Resolution::P1440, "1440"), + (Resolution::P2160, "2160"), +]; +const FPS: [(Fps, &str); 3] = [(Fps::F15, "15"), (Fps::F30, "30"), (Fps::F60, "60")]; + +const CODECS: [(ShareCodec, &str); 4] = [ + (ShareCodec::Auto, "Auto"), + (ShareCodec::Only(Codec::Av1), "AV1"), + (ShareCodec::Only(Codec::H265), "H265"), + (ShareCodec::Only(Codec::H264), "H264"), +]; + +#[derive(Clone, Copy, PartialEq, Eq)] +pub(super) enum AudioMode { + Off, + Everything, + App, +} + +impl AudioMode { + const ALL: [(Self, &'static str); 3] = [ + (Self::Off, "Off"), + (Self::Everything, "All"), + (Self::App, "Pick"), + ]; + + fn of(audio: &ShareAudio) -> Self { + match audio { + ShareAudio::Off => Self::Off, + ShareAudio::Everything => Self::Everything, + ShareAudio::Source(_) => Self::App, + } + } + + fn audio(self, first: String) -> ShareAudio { + match self { + Self::Off => ShareAudio::Off, + Self::Everything => ShareAudio::Everything, + Self::App => ShareAudio::Source(first), + } + } +} + +pub(super) struct Viewer { + user_id: String, + generation: Option, + frame: Option>, + fullscreen: bool, + volume: Entity, + _subscriptions: Vec, + _tick: Task<()>, +} + +impl Yumush { + pub(super) fn load_shares(&self, community_id: String, cx: &mut Context) { + let network = self.network.clone(); + + cx.spawn(async move |this, cx| { + let Ok(shares) = network.shares(&community_id).await else { + return; + }; + let _ = this.update(cx, |yumush, cx| { + yumush.chat.shares.insert(community_id, shares); + cx.notify(); + }); + }) + .detach(); + } + + pub(super) fn toggle_share(&mut self, window: &mut Window, cx: &mut Context) { + let network = self.network.clone(); + let sharing = network.sharing(); + + cx.spawn_in(window, async move |this, cx| { + if sharing { + let _ = network.stop_share().await; + } else if let Err(error) = network.start_share().await { + notify_error(&this, cx, error); + } + let _ = this.update(cx, |_, cx| cx.notify()); + }) + .detach(); + } + + fn update_share(&mut self, cx: &mut Context, change: impl FnOnce(&mut ShareSettings)) { + change(&mut self.settings.share); + settings::save(&self.settings); + self.network.set_share_settings(self.settings.share.clone()); + cx.notify(); + } + + pub(super) fn refresh_share_apps(&self, cx: &mut Context) { + let network = self.network.clone(); + + cx.spawn(async move |this, cx| { + let apps = cx + .background_executor() + .spawn(async move { network.audio_apps() }) + .await; + let _ = this.update(cx, |yumush, cx| { + yumush.share_apps = apps; + cx.notify(); + }); + }) + .detach(); + } + + pub(super) fn set_share_resolution(&mut self, resolution: Resolution, cx: &mut Context) { + self.update_share(cx, |settings| settings.top.resolution = resolution); + } + + pub(super) fn set_share_codec(&mut self, codec: ShareCodec, cx: &mut Context) { + self.update_share(cx, |settings| settings.codec = codec); + } + + pub(super) fn set_share_fps(&mut self, fps: Fps, cx: &mut Context) { + self.update_share(cx, |settings| settings.top.fps = fps); + } + + pub(super) fn set_share_audio_mode(&mut self, mode: AudioMode, cx: &mut Context) { + let first = self + .share_apps + .first() + .map(|app| app.node.clone()) + .unwrap_or_default(); + self.update_share(cx, |settings| settings.audio = mode.audio(first)); + self.refresh_share_apps(cx); + } + + pub(super) fn set_share_source(&mut self, node: String, cx: &mut Context) { + self.update_share(cx, |settings| settings.audio = ShareAudio::Source(node)); + } + + pub(super) fn set_share_excluded( + &mut self, + name: String, + excluded: bool, + cx: &mut Context, + ) { + self.update_share(cx, |settings| { + settings.excluded.retain(|app| *app != name); + if excluded { + settings.excluded.push(name); + } + }); + } + + pub(super) fn set_share_watch(&mut self, watch: WatchQuality, cx: &mut Context) { + self.update_share(cx, |settings| settings.watch = watch); + } + + pub(super) fn is_watching(&self, user_id: &str) -> bool { + self.chat + .viewer + .as_ref() + .is_some_and(|viewer| viewer.user_id == user_id) + } + + pub(super) fn toggle_viewer( + &mut self, + user_id: String, + window: &mut Window, + cx: &mut Context, + ) { + let watching = self.is_watching(&user_id); + self.close_viewer(cx); + if watching { + return; + } + + let volume_level = self.settings.share.volume; + let volume = cx.new(|_| { + SliderState::new() + .min(0.) + .max(100.) + .default_value(volume_level) + }); + let subscriptions = vec![cx.subscribe(&volume, |this, _, event: &SliderEvent, cx| { + if let SliderEvent::Change(value) = event { + let volume = value.start(); + 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: user_id.clone(), + generation: None, + frame: None, + fullscreen: false, + volume, + _subscriptions: subscriptions, + _tick: tick, + }); + + let network = self.network.clone(); + cx.spawn_in(window, async move |this, cx| { + if let Err(error) = network.watch_share(&user_id).await { + notify_error(&this, cx, error); + } + }) + .detach(); + cx.notify(); + } + + pub(super) fn close_viewer(&mut self, cx: &mut Context) { + let Some(viewer) = self.chat.viewer.take() else { + return; + }; + let user_id = viewer.user_id.clone(); + if let Some(frame) = viewer.frame { + cx.drop_image(frame, None); + } + let network = self.network.clone(); + cx.spawn(async move |_, _| { + let _ = network.unwatch_share(&user_id).await; + }) + .detach(); + cx.notify(); + } + + fn tick_viewer(&mut self, cx: &mut Context) { + let Some(viewer) = self.chat.viewer.as_mut() else { + return; + }; + let Some(frame) = self.network.share_frame(&viewer.user_id) else { + return; + }; + if viewer.generation == Some(frame.generation) { + return; + } + viewer.generation = Some(frame.generation); + let next = to_render_image(&frame); + if let Some(old) = std::mem::replace(&mut viewer.frame, next) { + cx.drop_image(old, None); + } + cx.notify(); + } + + pub(super) fn toggle_fullscreen(&mut self, cx: &mut Context) { + if let Some(viewer) = self.chat.viewer.as_mut() { + viewer.fullscreen = !viewer.fullscreen; + } + cx.notify(); + } + + pub(super) fn share_controls( + &self, + entity: &Entity, + palette: Palette, + ) -> impl IntoElement { + let sharing = self.network.sharing(); + let toggle = entity.clone(); + let refresh = entity.clone(); + let settings = entity.clone(); + + div() + .flex() + .items_center() + .gap(px(2.)) + .child( + clickable("share_toggle", palette, move |window, cx| { + toggle.update(cx, |yumush, cx| yumush.toggle_share(window, cx)); + }) + .tip(if sharing { + "Stop sharing" + } else { + "Share screen" + }) + .size(px(26.)) + .flex() + .items_center() + .justify_center() + .rounded(px(6.)) + .text_color(if sharing { palette.ok } else { palette.muted }) + .child( + Icon::new(if sharing { + IconName::ScreenShareOff + } else { + IconName::ScreenShare + }) + .w(px(14.)) + .h(px(14.)), + ), + ) + .child( + Popover::new("share_settings") + .anchor(Anchor::BottomLeft) + .appearance(false) + .trigger(Trigger::new( + div() + .id("share_settings_button") + .on_mouse_down(MouseButton::Left, move |_, _, cx| { + refresh.update(cx, |yumush, cx| yumush.refresh_share_apps(cx)); + }) + .tip("Share settings") + .size(px(26.)) + .flex() + .items_center() + .justify_center() + .rounded(px(6.)) + .text_color(palette.muted) + .child(Icon::new(IconName::SlidersHorizontal).w(px(14.)).h(px(14.))), + )) + .content(move |_, _, cx| { + let entity = settings.clone(); + pop_in( + "share_settings_card", + settings_card(&entity, entity.read(cx), palette), + Anchor::BottomLeft, + ) + }), + ) + } + + pub(super) fn inline_viewer(&self, entity: &Entity, palette: Palette) -> Option
{ + let viewer = self + .chat + .viewer + .as_ref() + .filter(|viewer| !viewer.fullscreen)?; + Some(self.viewer_pane(viewer, entity, palette)) + } + + pub(super) fn fullscreen_viewer(&self, entity: &Entity, palette: Palette) -> Option
{ + let viewer = self + .chat + .viewer + .as_ref() + .filter(|viewer| viewer.fullscreen && self.chat.view == View::Chat)?; + Some( + self.viewer_pane(viewer, entity, palette) + .absolute() + .inset_0(), + ) + } + + fn share_top(&self, user_id: &str) -> Quality { + self.chat + .selected_community_id + .as_ref() + .and_then(|community_id| self.chat.shares.get(community_id)) + .and_then(|shares| shares.iter().find(|share| share.user_id == user_id)) + .map_or(SHARE_QUALITY, |share| share.source.top) + } + + fn viewer_pane(&self, viewer: &Viewer, entity: &Entity, palette: Palette) -> Div { + let (fullscreen_icon, fullscreen_tip) = if viewer.fullscreen { + (IconName::Minimize, "Exit fullscreen") + } else { + (IconName::Maximize, "Fullscreen") + }; + let top = self.share_top(&viewer.user_id); + + div() + .flex_1() + .min_h_0() + .relative() + .occlude() + .bg(gpui_kit::black()) + .children( + viewer + .frame + .clone() + .map(|frame| img(frame).size_full().object_fit(ObjectFit::Contain)), + ) + .child( + div() + .absolute() + .left(px(10.)) + .right(px(10.)) + .bottom(px(10.)) + .p(px(6.)) + .flex() + .items_center() + .gap(px(8.)) + .rounded(px(8.)) + .border_1() + .border_color(palette.border) + .bg(palette.panel) + .occlude() + .text_size(text(12.)) + .child(quality_chips( + entity, + self.settings.share.watch, + top, + palette, + )) + .child(div().flex_1()) + .child( + Icon::new(IconName::Volume2) + .w(px(14.)) + .h(px(14.)) + .text_color(palette.muted), + ) + .child(Slider::new(&viewer.volume).bg(palette.muted).w(px(80.))) + .child(icon_button( + "share_fullscreen".to_string(), + palette, + fullscreen_icon, + fullscreen_tip, + entity_action(entity, |yumush, _, cx| yumush.toggle_fullscreen(cx)), + )) + .child(icon_button( + "share_close".to_string(), + palette, + IconName::X, + "Close", + entity_action(entity, |yumush, _, cx| yumush.close_viewer(cx)), + )), + ) + } +} + +fn quality_chips( + entity: &Entity, + watch: WatchQuality, + top: Quality, + palette: Palette, +) -> Div { + let fps = match watch { + WatchQuality::Auto => top.fps, + WatchQuality::Fixed(quality) => quality.fps, + }; + let resolutions = std::iter::once((WatchQuality::Auto, "Auto")).chain( + RESOLUTIONS + .into_iter() + .filter(|(resolution, _)| resolution.height() <= top.resolution.height()) + .map(|(resolution, label)| (WatchQuality::Fixed(Quality { resolution, fps }), label)), + ); + let row = div().flex().items_center().gap(px(6.)).child(segmented( + resolutions, + watch, + entity, + palette, + Yumush::set_share_watch, + )); + + match watch { + WatchQuality::Auto => row, + WatchQuality::Fixed(quality) => { + let fps = FPS + .into_iter() + .filter(|(fps, _)| fps.value() <= top.fps.value()) + .map(|(fps, label)| { + ( + WatchQuality::Fixed(Quality { + resolution: quality.resolution, + fps, + }), + label, + ) + }); + row.child(segmented( + fps, + watch, + entity, + palette, + Yumush::set_share_watch, + )) + } + } +} + +pub(super) fn share_badge( + entity: &Entity, + user_id: &str, + palette: Palette, +) -> impl IntoElement { + let entity = entity.clone(); + let user_id = user_id.to_string(); + + clickable( + format!("share_badge_{user_id}"), + palette, + move |window, cx| { + let user_id = user_id.clone(); + entity.update(cx, |yumush, cx| yumush.toggle_viewer(user_id, window, cx)); + }, + ) + .tip("Watch") + .ml(px(6.)) + .h(px(18.)) + .px(px(5.)) + .flex() + .items_center() + .gap(px(3.)) + .rounded(px(4.)) + .bg(palette.alert) + .text_color(palette.on_accent) + .text_size(text(10.)) + .font_weight(FontWeight::SEMIBOLD) + .child(Icon::new(IconName::ScreenShare).w(px(10.)).h(px(10.))) + .child("Live") +} + +fn settings_card(entity: &Entity, yumush: &Yumush, palette: Palette) -> Div { + let settings = &yumush.settings.share; + + div() + .w(px(320.)) + .p(px(10.)) + .flex() + .flex_col() + .gap(px(12.)) + .text_size(text(12.)) + .rounded(px(8.)) + .border_1() + .border_color(palette.border) + .bg(palette.panel) + .child(field( + "Resolution", + segmented( + RESOLUTIONS, + settings.top.resolution, + entity, + palette, + Yumush::set_share_resolution, + ), + palette, + )) + .child(field( + "FPS", + segmented( + FPS, + settings.top.fps, + entity, + palette, + Yumush::set_share_fps, + ), + palette, + )) + .child(field( + "Codec", + segmented( + CODECS.into_iter().filter(|(codec, _)| match codec { + ShareCodec::Auto => true, + ShareCodec::Only(codec) => capabilities().encode.contains(codec), + }), + settings.codec, + entity, + palette, + Yumush::set_share_codec, + ), + palette, + )) + .child(field( + "Audio", + segmented( + AudioMode::ALL, + AudioMode::of(&settings.audio), + entity, + palette, + Yumush::set_share_audio_mode, + ), + palette, + )) + .children(audio_list(entity, yumush, palette)) +} + +fn audio_list(entity: &Entity, yumush: &Yumush, palette: Palette) -> Option { + let settings = &yumush.settings.share; + + match &settings.audio { + ShareAudio::Off => None, + ShareAudio::Everything => { + let rows = div() + .flex() + .flex_col() + .gap(px(2.)) + .children( + yumush + .share_apps + .iter() + .filter(|app| app.kind == AudioKind::App) + .map(|app| exclude_row(entity, settings, app)), + ); + Some(field("Exclude", app_list(rows), palette).into_any_element()) + } + ShareAudio::Source(selected) => Some( + app_list(pick_list( + entity, + selected.as_str(), + &yumush.share_apps, + palette, + )) + .into_any_element(), + ), + } +} + +fn app_list(rows: impl IntoElement) -> impl IntoElement { + div() + .id("share_apps") + .max_h(px(160.)) + .overflow_y_scroll() + .child(rows) +} + +fn pick_list( + entity: &Entity, + selected: &str, + apps: &[AudioApp], + palette: Palette, +) -> Div { + let groups = [ + (AudioKind::App, "Apps"), + (AudioKind::Output, "Outputs"), + (AudioKind::Input, "Inputs"), + ]; + + div() + .flex() + .flex_col() + .gap(px(8.)) + .children(groups.into_iter().filter_map(|(kind, label)| { + let rows: Vec<_> = apps + .iter() + .filter(|app| app.kind == kind) + .map(|app| pick_row(entity, selected == app.node, app, palette)) + .collect(); + (!rows.is_empty()).then(|| group(label, rows, palette)) + })) +} + +fn group(label: &'static str, rows: Vec, palette: Palette) -> Div { + div() + .flex() + .flex_col() + .gap(px(2.)) + .child( + div() + .px(px(8.)) + .text_size(text(11.)) + .text_color(palette.muted) + .child(label), + ) + .children(rows) +} + +fn field(label: &'static str, control: impl IntoElement, palette: Palette) -> Div { + div() + .flex() + .flex_col() + .gap(px(6.)) + .child( + div() + .text_size(text(11.)) + .text_color(palette.muted) + .child(label), + ) + .child(control) +} + +fn row_style(item: E) -> E { + item.h(px(28.)) + .px(px(8.)) + .flex() + .items_center() + .gap(px(8.)) + .rounded(px(6.)) +} + +fn name_cell(name: String) -> Div { + div().flex_1().min_w_0().truncate().child(name) +} + +fn exclude_row(entity: &Entity, settings: &ShareSettings, app: &AudioApp) -> impl IntoElement { + let entity = entity.clone(); + let name = app.name.clone(); + let included = !settings.excluded.contains(&app.name); + + row_style(div()) + .child(name_cell(app.name.clone())) + .child( + div().flex_shrink_0().child( + Switch::new(format!("share_app_{}", app.node)) + .checked(included) + .on_change(move |checked, _, cx| { + let name = name.clone(); + let included = *checked; + entity.update(cx, |yumush, cx| { + yumush.set_share_excluded(name, !included, cx) + }); + }), + ), + ) +} + +fn pick_row( + entity: &Entity, + chosen: bool, + app: &AudioApp, + palette: Palette, +) -> impl IntoElement { + let entity = entity.clone(); + let node = app.node.clone(); + + row_style(clickable( + format!("share_app_{}", app.node), + palette, + move |_, cx| { + let node = node.clone(); + entity.update(cx, |yumush, cx| yumush.set_share_source(node, cx)); + }, + )) + .child(name_cell(app.name.clone())) + .children(chosen.then(|| { + Icon::new(IconName::Check) + .w(px(14.)) + .h(px(14.)) + .flex_shrink_0() + .text_color(palette.ok) + })) +} diff --git a/crates/client/src/gui/sidebar.rs b/crates/client/src/gui/sidebar.rs index 2784521..49ecc14 100644 --- a/crates/client/src/gui/sidebar.rs +++ b/crates/client/src/gui/sidebar.rs @@ -187,6 +187,7 @@ impl Yumush { ), ), ) + .child(self.share_controls(entity, palette)) .child(icon_button( "voice_panel_leave".to_string(), palette, @@ -205,10 +206,10 @@ impl Yumush { .appearance(false) .trigger(Trigger::new(panel)) .content(move |_, _, cx| { - let samples = &stats_entity.read(cx).chat.voice_samples; + let chat = &stats_entity.read(cx).chat; pop_in( "voice_stats_card", - voice_stats::stats_card(samples, palette), + voice_stats::stats_card(chat, &stats_entity, palette), Anchor::BottomLeft, ) }), @@ -995,7 +996,7 @@ fn entry( .children(trailing) } -fn icon_button( +pub(super) fn icon_button( id: String, palette: Palette, icon: IconName, diff --git a/crates/client/src/gui/voice_stats.rs b/crates/client/src/gui/voice_stats.rs index b9df84c..91eb84d 100644 --- a/crates/client/src/gui/voice_stats.rs +++ b/crates/client/src/gui/voice_stats.rs @@ -1,16 +1,29 @@ use std::collections::VecDeque; +use common::share::Layer; use gpui_kit::{ - Div, FontWeight, Hsla, ParentElement, Styled, div, hsla, prelude::FluentBuilder as _, px, + Context, Div, Entity, FontWeight, Hsla, ParentElement, Styled, div, hsla, + prelude::FluentBuilder as _, px, }; -use super::{Palette, text}; +use super::{Palette, Yumush, chat::Chat, settings_page::segmented, text}; +use crate::media::decode::Engine; +use crate::share::session::{LayerStats, WatchStats}; use crate::voice::VoiceSample; pub const SAMPLE_HISTORY: usize = 60; const GRAPH_HEIGHT: f32 = 32.; const PING_SCALE: f32 = 150.; const LOSS_SCALE: f32 = 10.; +const GOOD_LOSS: f32 = 2.; +const FAIR_LOSS: f32 = 8.; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum StatsTab { + Voice, + Sharing, + Watching, +} #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Quality { @@ -23,9 +36,19 @@ impl Quality { pub fn of(sample: &VoiceSample) -> Self { let loss = sample.traffic.loss * 100.; let jitter = sample.traffic.jitter_ms; - if sample.ping_ms < 100. && loss < 2. && jitter < 30. { + if sample.ping_ms < 100. && loss < GOOD_LOSS && jitter < 30. { + Self::Good + } else if sample.ping_ms < 200. && loss < FAIR_LOSS && jitter < 60. { + Self::Fair + } else { + Self::Poor + } + } + + fn of_loss(percent: f32) -> Self { + if percent < GOOD_LOSS { Self::Good - } else if sample.ping_ms < 200. && loss < 8. && jitter < 60. { + } else if percent < FAIR_LOSS { Self::Fair } else { Self::Poor @@ -53,7 +76,79 @@ pub fn quality(samples: &VecDeque) -> Option { samples.back().map(Quality::of) } -pub fn stats_card(samples: &VecDeque, palette: Palette) -> Div { +pub fn stats_card(chat: &Chat, entity: &Entity, palette: Palette) -> Div { + let share = &chat.share_sample; + let mut tabs = vec![(StatsTab::Voice, "Voice")]; + if !share.sending.is_empty() { + tabs.push((StatsTab::Sharing, "Sharing")); + } + if !share.watching.is_empty() { + tabs.push((StatsTab::Watching, "Watching")); + } + let selected = if tabs.iter().any(|(tab, _)| *tab == chat.stats_tab) { + chat.stats_tab + } else { + StatsTab::Voice + }; + + let body = match selected { + StatsTab::Voice => voice_body(&chat.voice_samples, palette), + StatsTab::Sharing => sharing_body(&share.sending, palette), + StatsTab::Watching => watching_body(&share.watching, chat, palette), + }; + let latest = chat.voice_samples.back(); + + div() + .w(px(280.)) + .p(px(14.)) + .flex() + .flex_col() + .gap(px(12.)) + .rounded(px(8.)) + .border_1() + .border_color(palette.border) + .bg(palette.panel) + .shadow_lg() + .child( + div() + .flex() + .items_center() + .justify_between() + .child( + div() + .font_weight(FontWeight::SEMIBOLD) + .text_color(palette.text) + .child("Connection"), + ) + .children( + (selected == StatsTab::Voice) + .then_some(latest) + .flatten() + .map(|sample| { + let quality = Quality::of(sample); + let color = quality.color(palette); + div() + .px(px(8.)) + .py(px(2.)) + .rounded_full() + .bg(color.opacity(0.15)) + .text_size(text(11.)) + .font_weight(FontWeight::MEDIUM) + .text_color(color) + .child(quality.label()) + }), + ), + ) + .children((tabs.len() > 1).then(|| segmented(tabs, selected, entity, palette, select_tab))) + .child(body) +} + +fn select_tab(yumush: &mut Yumush, tab: StatsTab, cx: &mut Context) { + yumush.chat.stats_tab = tab; + cx.notify(); +} + +fn voice_body(samples: &VecDeque, palette: Palette) -> Div { let latest = samples.back(); let value = |format: fn(&VoiceSample) -> String| latest.map_or("…".to_string(), format); let tiles = [ @@ -80,42 +175,7 @@ pub fn stats_card(samples: &VecDeque, palette: Palette) -> Div { ), ]; - div() - .w(px(280.)) - .p(px(14.)) - .flex() - .flex_col() - .gap(px(12.)) - .rounded(px(8.)) - .border_1() - .border_color(palette.border) - .bg(palette.panel) - .shadow_lg() - .child( - div() - .flex() - .items_center() - .justify_between() - .child( - div() - .font_weight(FontWeight::SEMIBOLD) - .text_color(palette.text) - .child("Connection"), - ) - .children(latest.map(|sample| { - let quality = Quality::of(sample); - let color = quality.color(palette); - div() - .px(px(8.)) - .py(px(2.)) - .rounded_full() - .bg(color.opacity(0.15)) - .text_size(text(11.)) - .font_weight(FontWeight::MEDIUM) - .text_color(color) - .child(quality.label()) - })), - ) + column() .child( div() .flex() @@ -125,14 +185,28 @@ pub fn stats_card(samples: &VecDeque, palette: Palette) -> Div { ) .child(graph( "Ping", - samples, - |sample| sample.ping_ms / PING_SCALE, + samples + .iter() + .map(|sample| { + ( + sample.ping_ms / PING_SCALE, + Quality::of(sample).color(palette), + ) + }) + .collect(), palette, )) .child(graph( "Loss", - samples, - |sample| sample.traffic.loss * 100. / LOSS_SCALE, + samples + .iter() + .map(|sample| { + ( + sample.traffic.loss * 100. / LOSS_SCALE, + Quality::of(sample).color(palette), + ) + }) + .collect(), palette, )) .children(latest.map(|sample| { @@ -143,6 +217,112 @@ pub fn stats_card(samples: &VecDeque, palette: Palette) -> Div { })) } +fn sharing_body(layers: &[LayerStats], palette: Palette) -> Div { + let upload: u32 = layers.iter().map(|layer| layer.kbps).sum(); + column() + .child(div().flex().flex_wrap().gap(px(6.)).child(tile( + "Upload", + format!("{upload} kbps"), + palette, + ))) + .children(layers.iter().map(|stat| { + row_line( + describe(Some(stat.layer), Some(stat.engine)), + format!("{} kbps · {:.0} fps", stat.kbps, stat.fps), + palette, + ) + })) +} + +fn watching_body(watching: &[(String, WatchStats)], chat: &Chat, palette: Palette) -> Div { + column().children(watching.iter().map(|(user_id, stats)| { + let name = chat.users.get(user_id).map_or_else( + || user_id.chars().take(8).collect(), + |user| user.username.clone(), + ); + let tiles = [ + ("Bitrate", format!("{} kbps", stats.kbps)), + ("FPS", format!("{:.0}", stats.fps)), + ("Loss", format!("{:.1} %", stats.loss * 100.)), + ("Delay", format!("{} ms", stats.delay_ms)), + ("Keyframes", stats.keyframes.to_string()), + ]; + column() + .child(row_line(name, describe(stats.layer, stats.engine), palette)) + .child( + div() + .flex() + .flex_wrap() + .gap(px(6.)) + .children(tiles.map(|(label, value)| tile(label, value, palette))), + ) + .child(graph( + "Loss", + chat.share_loss + .get(user_id) + .into_iter() + .flatten() + .map(|loss| { + ( + loss * 100. / LOSS_SCALE, + Quality::of_loss(loss * 100.).color(palette), + ) + }) + .collect(), + palette, + )) + })) +} + +fn column() -> Div { + div().flex().flex_col().gap(px(8.)) +} + +fn describe(layer: Option, engine: Option) -> String { + match (layer, engine) { + (Some(layer), Some(engine)) => format!( + "{} · {}p{} · {}", + layer.codec.name(), + layer.quality.resolution.height(), + layer.quality.fps.value(), + match engine { + Engine::Hardware => "HW", + Engine::Software => "SW", + } + ), + _ => "…".to_string(), + } +} + +fn row_line(left: String, right: String, palette: Palette) -> Div { + div() + .flex() + .items_center() + .justify_between() + .gap(px(6.)) + .px(px(8.)) + .py(px(4.)) + .rounded(px(6.)) + .bg(palette.window) + .child( + div() + .flex_1() + .min_w_0() + .truncate() + .text_size(text(11.)) + .font_weight(FontWeight::MEDIUM) + .text_color(palette.text) + .child(left), + ) + .child( + div() + .flex_none() + .text_size(text(11.)) + .text_color(palette.muted) + .child(right), + ) +} + fn tile(label: &'static str, value: String, palette: Palette) -> Div { div() .w(px(80.)) @@ -167,20 +347,12 @@ fn tile(label: &'static str, value: String, palette: Palette) -> Div { ) } -fn graph( - label: &'static str, - samples: &VecDeque, - level: fn(&VoiceSample) -> f32, - palette: Palette, -) -> Div { - let empty = SAMPLE_HISTORY.saturating_sub(samples.len()); - let bars = samples.iter().map(|sample| { - let height = level(sample).clamp(0.04, 1.) * GRAPH_HEIGHT; - div() - .flex_1() - .h(px(height)) - .rounded_t(px(1.)) - .bg(Quality::of(sample).color(palette)) +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) }); div() @@ -204,6 +376,6 @@ fn graph( .bg(palette.window) .children((0..empty).map(|_| div().flex_1())) .children(bars) - .when(samples.is_empty(), |this| this.opacity(0.5)), + .when(empty_bars, |this| this.opacity(0.5)), ) } diff --git a/crates/client/src/lib.rs b/crates/client/src/lib.rs index f703b25..c1efbf0 100644 --- a/crates/client/src/lib.rs +++ b/crates/client/src/lib.rs @@ -10,6 +10,7 @@ pub mod media; pub mod mutes; pub mod network; pub mod settings; +pub mod share; pub mod tray; pub mod voice; diff --git a/crates/client/src/media/convert.rs b/crates/client/src/media/convert.rs index c7c0bae..8719873 100644 --- a/crates/client/src/media/convert.rs +++ b/crates/client/src/media/convert.rs @@ -1,4 +1,5 @@ -const MAX_WIDTH: u32 = 1280; +pub const ATTACHMENT_WIDTH: u32 = 1280; +pub const SHARE_WIDTH: u32 = 1920; pub fn yuv_to_bgra( y: &[u8], @@ -8,11 +9,12 @@ pub fn yuv_to_bgra( uv_stride: usize, width: u32, height: u32, + max_width: u32, ) -> Option<(u32, u32, Vec)> { if width == 0 || height == 0 { return None; } - let step = width.div_ceil(MAX_WIDTH); + let step = width.div_ceil(max_width); let out_width = width.div_ceil(step); let out_height = height.div_ceil(step); let mut out = Vec::with_capacity(out_width as usize * out_height as usize * 4); @@ -48,7 +50,7 @@ mod tests { use super::*; fn bgra(luma: u8) -> Option<(u32, u32, Vec)> { - yuv_to_bgra(&[luma; 4], 2, &[128], &[128], 1, 2, 2) + yuv_to_bgra(&[luma; 4], 2, &[128], &[128], 1, 2, 2, ATTACHMENT_WIDTH) } #[test] diff --git a/crates/client/src/media/decode.rs b/crates/client/src/media/decode.rs index aaf3e96..5e52081 100644 --- a/crates/client/src/media/decode.rs +++ b/crates/client/src/media/decode.rs @@ -8,7 +8,7 @@ use std::{ time::{Duration, Instant}, }; -use common::constant::VOICE_SAMPLE_RATE; +use common::{constant::VOICE_SAMPLE_RATE, share::Codec}; use ec_core::frame::{Frame as CodecFrame, PixelFormat, VideoFrame}; use ec_core::packet::Packet; use ec_core::registry::{CodecId, CodecParameters, Decoder as CodecDecoder, SeekMode}; @@ -20,11 +20,12 @@ use tracing::warn; use super::{ Frame, Tracks, convert, - resample::{self, Resampler}, + resample::{self, Resampler, Stereo}, }; -use crate::voice::Playback; +use crate::voice::{PLAYBACK_CHANNELS, Playback}; -pub const RING_SAMPLES: usize = VOICE_SAMPLE_RATE as usize / 4; +pub const RING_FRAMES: usize = VOICE_SAMPLE_RATE as usize / 4; +pub const RING_SAMPLES: usize = RING_FRAMES * PLAYBACK_CHANNELS; const QUEUE_LIMIT: usize = 8; const BACKLOG_LIMIT: usize = 600; const LATE: f64 = 0.1; @@ -100,7 +101,7 @@ pub struct Shared { pub seek: Mutex>, pub clock: Mutex, pub video: Mutex