use std::collections::VecDeque; use std::time::{Duration, Instant}; use common::model::Id; use common::share::{Fps, Kind, Quality, Resolution}; use gpui_kit::{ AnyElement, AppContext as _, Context, Div, Entity, InteractiveElement, IntoElement, ParentElement, StatefulInteractiveElement, Styled, Task, Window, assets::IconName, div, prelude::FluentBuilder as _, px, }; use std::sync::atomic::{AtomicBool, Ordering}; use super::{ Tooltip as _, Yumush, media_view::into_render_image, notify_error, parts::{Ink, Text, Voice, caption, scrim, voice_line, words}, style::{Tokens, radius, size, space}, surface::Surface, }; use crate::lang::w; use crate::share::watch::WatchQuality; const SLOTS: usize = 6; const IDLE_TICK: Duration = Duration::from_millis(250); const FRAME_TICK: Duration = Duration::from_millis(16); const PUMP_STALL: Duration = Duration::from_millis(50); const TILE_W: f32 = size::THUMB * 1.5; const TILE_H: f32 = TILE_W * 9. / 16.; const TILE_QUALITY: WatchQuality = WatchQuality::Fixed(Quality { resolution: Resolution::P360, fps: Fps::F15, }); const WIDE: f32 = 16. / 9.; const GRID_GAP: f32 = super::style::stroke::LINE; #[derive(Clone, Copy, PartialEq, Eq)] pub(super) enum Stage { Strip, Grid, Hidden, } impl Stage { pub(super) fn quality(self) -> WatchQuality { match self { Stage::Grid => WatchQuality::Auto, Stage::Strip | Stage::Hidden => TILE_QUALITY, } } fn cover(self) -> bool { self != Stage::Grid } } pub(super) struct Tile { pub(super) shown: bool, pub(super) live: bool, pub(super) surface: Entity, } impl Yumush { fn tile_sources(&self) -> Vec<(Id, Kind)> { if self.chat.stage == Stage::Hidden { return Vec::new(); } self.stage_sources() } fn watch_quality(&self, source: (Id, Kind)) -> WatchQuality { if self.viewing() == Some(source) { WatchQuality::Auto } else { self.chat.stage.quality() } } fn watch_tile(&self, source: (Id, Kind), cx: &mut Context) { let (user_id, kind) = source; let network = self.network.clone(); let quality = self.chat.stage.quality(); let volume = self.settings.share.volume; let choice = self.settings.voice.choice.clone(); let top = self.share_top(user_id, kind); cx.spawn(async move |this, cx| { let watched = network .watch_share(user_id, kind, quality, top, volume, choice) .await; let live = watched.is_ok(); if let Err(error) = &watched { tracing::warn!("tile watch failed: {error}"); } let orphaned = this.update(cx, |yumush, _| { let Some(tile) = yumush.chat.session.tiles.get_mut(&source) else { return live && yumush.viewing() != Some(source); }; tile.live = live; if live { yumush .network .set_watch_quality(user_id, kind, yumush.watch_quality(source)); } false }); if let Ok(true) = orphaned { let _ = network.unwatch_share(user_id, kind).await; } }) .detach(); } pub(super) fn unwatch_tile(&self, (user_id, kind): (Id, Kind), cx: &mut Context) { let network = self.network.clone(); cx.spawn(async move |_, _| { let _ = network.unwatch_share(user_id, kind).await; }) .detach(); } pub(super) fn tick_tiles( &mut self, mut window: Option<&mut Window>, cx: &mut Context, ) -> bool { let wanted = self.tile_sources(); let viewing = self.viewing(); let mut changed = false; for &source in &wanted { if self.chat.session.tiles.contains_key(&source) { continue; } let network = self.network.clone(); let cover = self.chat.stage.cover(); let surface = cx.new(|cx| Surface::new(cover, network, source, cx)); let live = viewing == Some(source); self.chat.session.tiles.insert( source, Tile { shown: false, live, surface, }, ); changed = true; if !live { self.watch_tile(source, cx); } } let gone: Vec<(Id, Kind)> = self .chat .session .tiles .keys() .filter(|source| !wanted.contains(source)) .copied() .collect(); for source in gone { let Some(tile) = self.chat.session.tiles.remove(&source) else { continue; }; if let Some(frame) = tile .surface .update(cx, |surface, cx| surface.replace(None, cx)) { cx.drop_image(frame, window.as_deref_mut()); } if tile.live && viewing != Some(source) { self.unwatch_tile(source, cx); } changed = true; } for (&source, tile) in self.chat.session.tiles.iter_mut() { if viewing == Some(source) { continue; } let Some(frame) = self.network.share_frame(source.0, source.1) else { continue; }; let next = into_render_image(frame); changed |= !tile.shown && next.is_some(); tile.shown |= next.is_some(); if let Some(old) = tile .surface .update(cx, |surface, cx| surface.replace(next, cx)) { cx.drop_image(old, window.as_deref_mut()); } } if changed { cx.notify(); } !self.chat.session.tiles.is_empty() } pub(super) fn set_stage(&mut self, stage: Stage, cx: &mut Context) { self.chat.stage = stage; for (&source, tile) in &self.chat.session.tiles { self.network .set_watch_quality(source.0, source.1, self.watch_quality(source)); tile.surface .update(cx, |surface, cx| surface.set_cover(stage.cover(), cx)); } cx.notify(); } pub(super) fn toggle_camera(&mut self, window: &mut Window, cx: &mut Context) { if CAMERA_BUSY.load(Ordering::Relaxed) { return; } CAMERA_BUSY.store(true, Ordering::Relaxed); let network = self.network.clone(); let on = network.share_source(Kind::Camera).is_some(); let settings = self.settings.share.clone(); let device = settings.camera_device.clone(); cx.spawn_in(window, async move |this, cx| { let started = if on { let _ = network.stop(Kind::Camera).await; Ok(()) } else { network.start(Kind::Camera, &settings, None).await }; if let Err(error) = started { notify_error(&this, cx, error); } let _ = this.update(cx, |yumush, cx| yumush.settle_camera(device, cx)); }) .detach(); } pub(super) fn in_stage_chat(&self) -> bool { self.chat.voice_community().is_some() && self.chat.session.selected_community_id == self.chat.voice_community() } pub(super) fn stage_sources(&self) -> Vec<(Id, Kind)> { let Some(community_id) = self.chat.voice_community() else { return Vec::new(); }; let mut shares: Vec<&common::share::Share> = self .chat .session .shares .get(&community_id) .into_iter() .flatten() .collect(); shares.sort_by_key(|share| (share.kind != Kind::Camera, share.started_ms, share.user_id)); shares .into_iter() .map(|share| (share.user_id, share.kind)) .collect() } pub(super) fn stage_strip(&self, entity: &Entity, t: Tokens) -> Option { let visible = match self.chat.stage { Stage::Strip => true, Stage::Grid => self.chat.session.viewer.is_some(), Stage::Hidden => false, }; if !visible || !self.in_stage_chat() { return None; } let sources = self.stage_sources(); let (count, more) = strip_slots(self.chat.strip_size.0, sources.len()); (!sources.is_empty()).then(|| { div() .id("stage_strip") .relative() .w_full() .child(probe(entity.clone(), |yumush| &mut yumush.chat.strip_size)) .flex() .flex_shrink_0() .gap(px(space::LG)) .px(px(space::XL)) .pb(px(space::LG)) .children( sources .into_iter() .take(count) .map(|source| stage_tile(entity, self, t, source).into_any_element()), ) .children((more > 0).then(|| more_tile(entity, more, t).into_any_element())) }) } fn slots(&self, ids: &[Id]) -> (Vec, usize) { let speaking = |id: &Id| self.chat.session.waves.audible(*id); let mut shown: Vec = ids .iter() .filter(|id| speaking(id)) .take(SLOTS) .copied() .collect(); shown.extend( ids.iter() .filter(|id| !speaking(id)) .take(SLOTS - shown.len()) .copied(), ); shown.sort_by_key(|id| ids.iter().position(|other| other == id)); let more = ids.len() - shown.len(); (shown, more) } fn voice_captions(&self, ids: &[Id], t: Tokens) -> Vec
{ let (shown, more) = self.slots(ids); shown .into_iter() .filter_map(|id| self.chat.author(id)) .map(|user| { let bands = self .chat .session .waves .voice(user.id) .map(|bands| bands.iter().copied().collect::>()); let share = self .chat .session .waves .share(user.id) .map(|bands| bands.iter().copied().collect::>()); let voice = if self.chat.session.waves.speaking.contains(&user.id) { Voice::Live(t.person(user.id)) } else { Voice::Quiet }; let screen = self .chat .voice_community() .and_then(|community_id| { self.chat.share_of(community_id, user.id, Kind::Screen) }) .is_some(); caption( user.username.clone(), voice_line(bands.as_ref(), voice, t), t, ) .h(px(size::CONTROL_SM)) .children( screen.then(|| { super::call_bar::share_meter(share.as_ref(), t.person(user.id), t) }), ) }) .chain( (more > 0) .then(|| caption(w().common.more(more), voice_line(None, Voice::Quiet, t), t)), ) .collect() } pub(super) fn voice_band(&self, t: Tokens) -> Div { let ids = self .chat .voice_community() .map(|community_id| self.chat.voice_ids(community_id).to_vec()) .unwrap_or_default(); div() .flex() .flex_shrink_0() .gap(px(space::XL)) .px(px(space::XL)) .py(px(space::LG)) .children( self.voice_captions(&ids, t) .into_iter() .map(|caption| caption.flex_1().min_w_0()), ) } pub(super) fn stage_grid( &self, entity: &Entity, t: Tokens, cx: &gpui_kit::App, ) -> Option { if self.chat.stage != Stage::Grid || !self.in_stage_chat() || self .chat .session .viewer .as_ref() .is_some_and(|viewer| !viewer.fullscreen) { return None; } let sources = self.stage_sources(); if sources.is_empty() { return None; } let aspects: Vec = sources .iter() .map(|source| { self.chat .session .tiles .get(source) .map_or(WIDE, |tile| tile.surface.read(cx).aspect()) }) .collect(); let size = self.chat.grid_size; let columns = grid_columns(&aspects, size); let (cell_w, cell_h) = cell_size(sources.len(), columns, size); let mut cells = sources.into_iter().zip(aspects).map(|(source, aspect)| { let width = cell_w.min(cell_h * aspect); grid_cell(entity, self, t, source, (width, width / aspect)) }); let rows = (0..row_count(columns, cells.len())) .map(|_| { div() .flex() .justify_center() .items_center() .gap(px(GRID_GAP)) .children(cells.by_ref().take(columns).collect::>()) }) .collect::>(); Some( div() .flex_1() .min_h_0() .relative() .flex() .flex_col() .justify_center() .gap(px(GRID_GAP)) .child(probe(entity.clone(), |yumush| &mut yumush.chat.grid_size)) .children(rows), ) } } fn probe(entity: Entity, slot: fn(&mut Yumush) -> &mut (f32, f32)) -> impl IntoElement { gpui_kit::canvas( move |bounds, _, cx| { let size = (f32::from(bounds.size.width), f32::from(bounds.size.height)); entity.update(cx, |yumush, cx| { let stored = slot(yumush); if *stored != size { *stored = size; cx.notify(); } }); }, |_, _, _, _| {}, ) .absolute() .inset_0() } fn strip_slots(width: f32, count: usize) -> (usize, usize) { let fit = (((width - 2. * space::XL + space::LG) / (TILE_W + space::LG)).floor() as usize).max(1); if count <= fit { (count, 0) } else { let shown = fit - 1; (shown, count - shown) } } fn row_count(columns: usize, count: usize) -> usize { count.div_ceil(columns.max(1)) } fn cell_size(count: usize, columns: usize, (width, height): (f32, f32)) -> (f32, f32) { let rows = row_count(columns, count); ( (width - GRID_GAP * (columns - 1) as f32) / columns as f32, (height - GRID_GAP * (rows - 1) as f32) / rows as f32, ) } fn grid_columns(aspects: &[f32], size: (f32, f32)) -> usize { (1..=aspects.len().max(1)) .max_by(|a, b| { let area = |columns: usize| { let (cell_w, cell_h) = cell_size(aspects.len(), columns, size); aspects .iter() .map(|aspect| { let width = cell_w.min(cell_h * aspect); width * width / aspect }) .sum::() }; area(*a).total_cmp(&area(*b)) }) .unwrap_or(1) } pub(super) fn ticker(cx: &mut Context) -> Task<()> { cx.spawn(async move |this, cx| { let mut tick = IDLE_TICK; loop { cx.background_executor().timer(tick).await; 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.session.viewer.is_some() || !self.chat.session.tiles.is_empty() || self.media_playing() } fn pump(&mut self, window: &mut Window, cx: &mut Context) { self.pumping = false; self.pumped = Instant::now(); self.tick_viewer(Some(window), cx); self.tick_tiles(Some(window), cx); self.tick_player(window, cx); self.schedule_pump(window, cx); } fn idle_tick(&mut self, cx: &mut Context) -> bool { if self.pumped.elapsed() > PUMP_STALL { self.tick_viewer(None, cx); self.tick_tiles(None, 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 tile_surface(yumush: &Yumush, source: (Id, Kind)) -> Option> { yumush .chat .session .tiles .get(&source) .filter(|tile| tile.shown) .map(|tile| tile.surface.clone()) } fn stage_tile( entity: &Entity, yumush: &Yumush, t: Tokens, (user_id, kind): (Id, Kind), ) -> impl IntoElement { let entity = entity.clone(); let focused = yumush.is_watching(user_id, kind); let surface = tile_surface(yumush, (user_id, kind)); div() .id(format!("stage_{user_id}_{kind:?}")) .tip(w().camera_view.watch) .cursor_pointer() .flex() .flex_col() .flex_shrink_0() .gap(px(space::SM)) .w(px(TILE_W)) .on_click(move |_, window, cx| { entity.update(cx, |yumush, cx| { yumush.toggle_viewer(user_id, kind, window, cx) }); }) .child(tile_name(yumush, (user_id, kind), focused, t)) .child( div() .h(px(TILE_H)) .rounded(px(radius::MD)) .overflow_hidden() .bg(t.raise()) .children(surface), ) } fn more_tile(entity: &Entity, more: usize, t: Tokens) -> impl IntoElement { let entity = entity.clone(); div() .id("stage_more") .cursor_pointer() .flex() .flex_col() .flex_shrink_0() .gap(px(space::SM)) .w(px(TILE_W)) .on_click(move |_, _, cx| { entity.update(cx, |yumush, cx| { yumush.close_viewer(cx); yumush.set_stage(Stage::Grid, cx); }); }) .child(super::parts::band(space::XS).h(px(size::ICON)).child(words( w().camera_view.streams, Text::Label, Ink::Dim, t, ))) .child( div() .h(px(TILE_H)) .flex() .items_center() .justify_center() .rounded(px(radius::MD)) .bg(t.raise()) .child(words(format!("+{more}"), Text::Title, Ink::Paper, t)), ) } fn grid_cell( entity: &Entity, yumush: &Yumush, t: Tokens, (user_id, kind): (Id, Kind), (width, height): (f32, f32), ) -> AnyElement { let entity = entity.clone(); let surface = tile_surface(yumush, (user_id, kind)); div() .id(format!("grid_{user_id}_{kind:?}")) .w(px(width)) .h(px(height)) .flex_none() .relative() .overflow_hidden() .cursor_pointer() .tip(w().camera_view.watch) .on_click(move |_, window, cx| { entity.update(cx, |yumush, cx| { yumush.toggle_viewer(user_id, kind, window, cx) }); }) .child(div().absolute().inset_0().children(surface)) .child( tile_label(yumush, t, (user_id, kind)) .absolute() .left(px(space::MD)) .top(px(space::MD)), ) .into_any_element() } pub(super) fn tile_label(yumush: &Yumush, t: Tokens, source: (Id, Kind)) -> Div { let user_id = source.0; let muted = yumush.chat.session.server_muted.contains(&user_id) || (yumush.is_me(user_id) && yumush.chat.voice_flags().is_some_and(|(muted, _)| muted)); scrim(t) .child(tile_name(yumush, source, true, t)) .children(muted.then(|| super::parts::small_icon(IconName::MicOff).text_color(t.bad()))) } fn tile_name( yumush: &Yumush, (user_id, kind): (Id, Kind), focused: bool, t: super::style::Tokens, ) -> Div { let name = yumush .chat .author(user_id) .map_or_else(|| user_id.to_string(), |user| user.username.clone()); let audible = yumush.chat.session.waves.audible(user_id); let ink = if audible || focused { Ink::Paper } else { Ink::Dim }; super::parts::band(space::XS) .h(px(size::ICON)) .child( super::parts::small_icon(match kind { Kind::Camera => IconName::Video, Kind::Screen => IconName::ScreenShare, }) .text_color(if audible { t.person(user_id) } else { t.dim() }), ) .child( words(name, Text::Label, ink, t) .truncate() .when(audible, |name| name.text_color(t.person(user_id))), ) } pub(super) static CAMERA_BUSY: AtomicBool = AtomicBool::new(false); #[cfg(test)] mod tests { use super::{WIDE, grid_columns}; #[test] fn grid_columns_fill_the_shape() { assert_eq!(grid_columns(&[WIDE], (1300., 900.)), 1); assert_eq!(grid_columns(&[WIDE, WIDE], (1300., 900.)), 1); assert_eq!(grid_columns(&[WIDE, WIDE], (2400., 600.)), 2); assert_eq!(grid_columns(&[WIDE; 4], (1600., 900.)), 2); } }