diff --git a/crates/client/src/gui/camera_view.rs b/crates/client/src/gui/camera_view.rs index 3284491..d9858b9 100644 --- a/crates/client/src/gui/camera_view.rs +++ b/crates/client/src/gui/camera_view.rs @@ -4,10 +4,8 @@ use std::sync::Arc; use common::share::{Fps, Kind, Quality, Resolution}; use gpui_kit::{ AnyElement, Context, Entity, InteractiveElement, IntoElement, ObjectFit, ParentElement, - RenderImage, StatefulInteractiveElement, Styled, StyledImage, Task, Window, - assets::IconName, - component::Icon, - div, img, px, + RenderImage, StatefulInteractiveElement, Styled, StyledImage, Task, Window, assets::IconName, + component::Icon, div, img, px, }; use super::{ @@ -78,9 +76,10 @@ impl Yumush { let network = self.network.clone(); let volume = self.settings.share.volume; let choice = self.settings.voice.choice.clone(); + let top = self.share_top(user_id, kind); spawn_warn(cx, "tile watch", async move { network - .watch_share(user_id, kind, quality, volume, choice) + .watch_share(user_id, kind, quality, top, volume, choice) .await }); } @@ -93,12 +92,7 @@ impl Yumush { .copied() .collect(); for source in gone { - if let Some(frame) = self - .chat - .tiles - .remove(&source) - .and_then(|tile| tile.frame) - { + if let Some(frame) = self.chat.tiles.remove(&source).and_then(|tile| tile.frame) { cx.drop_image(frame, None); } if viewing != Some(source) { @@ -280,10 +274,7 @@ pub(super) fn ticker(cx: &mut Context) -> Task<()> { cx.spawn(async move |this, cx| { loop { cx.background_executor().timer(FRAME_TICK).await; - if this - .update(cx, |yumush, cx| yumush.tick_tiles(cx)) - .is_err() - { + if this.update(cx, |yumush, cx| yumush.tick_tiles(cx)).is_err() { break; } } @@ -468,11 +459,10 @@ fn grid_cell( .flex() .items_center() .gap(px(4.)) - .children((kind == Kind::Screen).then(|| { - Icon::new(share_view::kind_icon(kind)) - .w(px(12.)) - .h(px(12.)) - })) + .children( + (kind == Kind::Screen) + .then(|| Icon::new(share_view::kind_icon(kind)).w(px(12.)).h(px(12.))), + ) .child(name.to_string()), ); diff --git a/crates/client/src/gui/chat.rs b/crates/client/src/gui/chat.rs index 006c4e7..1efb65f 100644 --- a/crates/client/src/gui/chat.rs +++ b/crates/client/src/gui/chat.rs @@ -296,7 +296,9 @@ impl Chat { &message_input, window, |this, input, event, window, cx| match event { - InputEvent::PressEnter { shift: false, .. } => this.submit_composer(input, window, cx), + InputEvent::PressEnter { shift: false, .. } => { + this.submit_composer(input, window, cx) + } InputEvent::Change => this.send_typing(cx), _ => {} }, @@ -531,8 +533,12 @@ impl Chat { pub fn focus(&self, window: &mut Window, cx: &mut Context) { match self.selected_community_id { - Some(_) => self.message_input.update(cx, |input, cx| input.focus(window, cx)), - None => self.search_input.update(cx, |input, cx| input.focus(window, cx)), + Some(_) => self + .message_input + .update(cx, |input, cx| input.focus(window, cx)), + None => self + .search_input + .update(cx, |input, cx| input.focus(window, cx)), } } @@ -726,8 +732,11 @@ impl Chat { self.delete_step = DeleteStep::Idle; } self.selected_community_id = community_id; - self.users - .extend(self.members.drain(..).map(|member| (member.user.id, member.user))); + self.users.extend( + self.members + .drain(..) + .map(|member| (member.user.id, member.user)), + ); self.bans.clear(); self.logs.clear(); self.pending_user_delete = None; @@ -2503,35 +2512,33 @@ impl Yumush { .when(index > 0, |this| this.ml(px(-6.))), ) })) - .children( - self.in_stage_chat().then(|| { - div() - .ml(px(8.)) - .flex() - .items_center() - .p(px(2.)) - .gap(px(2.)) - .rounded(px(6.)) - .border_1() - .border_color(palette.border) - .child(stage_button( - entity, - palette, - Stage::Strip, - current == Stage::Strip, - IconName::GalleryHorizontal, - "Strip", - )) - .child(stage_button( - entity, - palette, - Stage::Grid, - current == Stage::Grid, - IconName::LayoutGrid, - "Grid", - )) - }), - ), + .children(self.in_stage_chat().then(|| { + div() + .ml(px(8.)) + .flex() + .items_center() + .p(px(2.)) + .gap(px(2.)) + .rounded(px(6.)) + .border_1() + .border_color(palette.border) + .child(stage_button( + entity, + palette, + Stage::Strip, + current == Stage::Strip, + IconName::GalleryHorizontal, + "Strip", + )) + .child(stage_button( + entity, + palette, + Stage::Grid, + current == Stage::Grid, + IconName::LayoutGrid, + "Grid", + )) + })), ) } @@ -2932,14 +2939,16 @@ fn render_message( .child( div() .min_w_0() - .when(message.body.contains("```"), |this| this.w_full()) + .when(message.body.contains("```"), |this| { + this.w_full() + }) .child( - TextView::markdown( - format!("message-body-{}", message.id), - hard_breaks(&message.body), - ) - .selectable(true), - ), + TextView::markdown( + format!("message-body-{}", message.id), + hard_breaks(&message.body), + ) + .selectable(true), + ), ) .when(message.edited, |this| { this.child( @@ -3056,9 +3065,10 @@ fn hard_breaks(body: &str) -> String { fenced = !fenced; return line.to_string(); } - match fenced || line.trim().is_empty() { - true => line.to_string(), - false => format!("{line} "), + match (fenced, line.trim().is_empty()) { + (true, _) => line.to_string(), + (false, true) => "\u{a0} ".to_string(), + (false, false) => format!("{line} "), } }) .collect(); @@ -3088,6 +3098,10 @@ fn stage_button( .justify_center() .rounded(px(4.)) .when(active, |this| this.bg(palette.hover)) - .text_color(if active { palette.accent } else { palette.muted }) + .text_color(if active { + palette.accent + } else { + palette.muted + }) .child(Icon::new(icon).w(px(14.)).h(px(14.))) } diff --git a/crates/client/src/gui/composer.rs b/crates/client/src/gui/composer.rs index 10a678a..4e59e3e 100644 --- a/crates/client/src/gui/composer.rs +++ b/crates/client/src/gui/composer.rs @@ -17,16 +17,20 @@ use gpui_kit::{ IntoElement, KeyBinding, MouseButton, ParentElement, Styled, Window, actions, assets::IconName, component::{ - Icon, WindowExt, checkbox::Checkbox, input::{InputEvent, InputState, TextareaState}, notification::Notification, - popover::Popover, text::TextView, + Icon, WindowExt, + checkbox::Checkbox, + input::{InputEvent, InputState, TextareaState}, + notification::Notification, + popover::Popover, + text::TextView, }, div, px, }; use super::{ - Palette, Trigger, Yumush, clickable, + Palette, Trigger, Yumush, chat::{Chat, TYPING_SEND_INTERVAL}, - hoverable, new_input, notify_error, pop_in, primary_button, + clickable, hoverable, new_input, notify_error, pop_in, primary_button, }; actions!(composer, [Bold, Italic, Code, Strike]); @@ -141,9 +145,7 @@ fn reply_bar( .map_or("unknown", |user| user.username.as_str()) .to_string(); let quote = message - .map(|message| { - super::message_actions::message_text(message) - }) + .map(super::message_actions::message_text) .unwrap_or_default(); bar(palette) @@ -197,7 +199,13 @@ impl Yumush { if self.chat.media.uploading() { return; } - let body = input.read(cx).text().to_string(); + let body = input + .read(cx) + .text() + .to_string() + .trim_end() + .trim_start_matches(['\n', '\r']) + .to_string(); match self.chat.composer.clone() { Composer::Compose { reply } => self.create_message(reply, body, input, window, cx), @@ -686,19 +694,23 @@ pub fn plus_popover(chat: &Chat, entity: &Entity, palette: Palette) -> i .min_w_0() .child(compact_field(palette, option)), ) - .children((options.len() > MINIMUM_POLL_OPTIONS && !trailing_blank).then(|| { - icon_button( - format!("poll_remove_{index}"), - palette, - IconName::Close, - "Remove option", - move |_, cx| { - remove.update(cx, |yumush, cx| { - yumush.remove_poll_option(index, cx) - }); + .children( + (options.len() > MINIMUM_POLL_OPTIONS && !trailing_blank).then( + || { + icon_button( + format!("poll_remove_{index}"), + palette, + IconName::Close, + "Remove option", + move |_, cx| { + remove.update(cx, |yumush, cx| { + yumush.remove_poll_option(index, cx) + }); + }, + ) }, - ) - })) + ), + ) })) .child( div() @@ -719,44 +731,44 @@ pub fn plus_popover(chat: &Chat, entity: &Entity, palette: Palette) -> i .px(px(6.)) .py(px(2.)) .rounded(px(4.)) - .text_color(if active { palette.accent } else { palette.muted }) + .text_color(if active { + palette.accent + } else { + palette.muted + }) .bg(palette.accent.opacity(if active { 0.15 } else { 0. })) .child(label) })), ) .child( - div() - .flex() - .items_center() - .justify_between() - .child( - div() - .flex() - .items_center() - .gap(px(12.)) - .child( - Checkbox::new("poll_multiple") - .label("Multiple answers") - .checked(multiple) - .on_click(move |_, _, cx| { - toggle.update(cx, |yumush, cx| { - yumush.chat.poll_multiple = - !yumush.chat.poll_multiple; - cx.notify(); - }) - }), - ) - .child( - Checkbox::new("poll_public") - .label("Show voters") - .checked(public) - .on_click(move |_, _, cx| { - toggle_public.update(cx, |yumush, cx| { - yumush.toggle_poll_public(cx) - }) - }), - ), - ), + div().flex().items_center().justify_between().child( + div() + .flex() + .items_center() + .gap(px(12.)) + .child( + Checkbox::new("poll_multiple") + .label("Multiple answers") + .checked(multiple) + .on_click(move |_, _, cx| { + toggle.update(cx, |yumush, cx| { + yumush.chat.poll_multiple = + !yumush.chat.poll_multiple; + cx.notify(); + }) + }), + ) + .child( + Checkbox::new("poll_public") + .label("Show voters") + .checked(public) + .on_click(move |_, _, cx| { + toggle_public.update(cx, |yumush, cx| { + yumush.toggle_poll_public(cx) + }) + }), + ), + ), ) .child( primary_button("poll_create", palette, move |window, cx| { diff --git a/crates/client/src/gui/poll.rs b/crates/client/src/gui/poll.rs index b514008..2245b21 100644 --- a/crates/client/src/gui/poll.rs +++ b/crates/client/src/gui/poll.rs @@ -1,15 +1,15 @@ -use common::model::Id; use common::call::{ClosePoll, MyVotes, Vote}; +use common::model::Id; use common::model::{Message, Poll, Rank, User}; use common::time::{DAY_MILLIS, HOUR_MILLIS, MINUTE_MILLIS, now_ms}; use gpui_kit::{ Anchor, AnyElement, Context, Div, Entity, FontWeight, InteractiveElement, IntoElement, - ParentElement, StatefulInteractiveElement, Styled, Window, assets::IconName, component::Icon, component::popover::Popover, - div, prelude::FluentBuilder as _, px, relative, + ParentElement, StatefulInteractiveElement, Styled, Window, assets::IconName, component::Icon, + component::popover::Popover, div, prelude::FluentBuilder as _, px, relative, }; use super::{ - Palette, Trigger, Tooltip as _, Yumush, avatar, + Palette, Tooltip as _, Trigger, Yumush, avatar, chat::Chat, clickable, hoverable, pop_in, text, widget::{icon_button, panel, spawn_done}, @@ -50,7 +50,12 @@ pub enum PollMode<'a> { Snapshot(Id), } -fn status_icon(id: String, icon: IconName, tip: &'static str, palette: Palette) -> impl IntoElement { +fn status_icon( + id: String, + icon: IconName, + tip: &'static str, + palette: Palette, +) -> impl IntoElement { div() .id(id) .tip(tip) @@ -119,13 +124,7 @@ fn voters_popover(key: &str, poll: &Poll, entity: &Entity, palette: Pale .items_center() .gap(px(8.)) .text_size(text(12.)) - .child(avatar( - palette, - user, - px(18.), - text(8.), - &chat.avatars, - )) + .child(avatar(palette, user, px(18.), text(8.), &chat.avatars)) .child( div() .flex_1() @@ -208,11 +207,7 @@ pub fn poll_card( let next = me_id .map(|_| next_votes(&mine, position as u32, poll.multiple)) .unwrap_or_default(); - let voters_here: &[Id] = if poll.public { - &option.voter_ids - } else { - &[] - }; + let voters_here: &[Id] = if poll.public { &option.voter_ids } else { &[] }; let entity = entity.clone(); let id = format!("poll_option_{key}_{position}"); match vote_id { @@ -278,16 +273,20 @@ pub fn poll_card( div() .flex() .items_center() - .children(voters_here.iter().take(3).enumerate().filter_map( - |(index, id)| { - chat.author(*id).map(|user| { - avatar(palette, user, px(18.), text(8.), &chat.avatars) - .border_2() - .border_color(palette.panel) - .when(index > 0, |el| el.ml(px(-6.))) - }) - }, - )) + .children( + voters_here + .iter() + .take(3) + .enumerate() + .filter_map(|(index, id)| { + chat.author(*id).map(|user| { + avatar(palette, user, px(18.), text(8.), &chat.avatars) + .border_2() + .border_color(palette.panel) + .when(index > 0, |el| el.ml(px(-6.))) + }) + }), + ) .children((voters_here.len() > 3).then(|| { div() .ml(px(4.)) @@ -312,17 +311,14 @@ pub fn poll_card( voters_label(voters).into_any_element() }; - let timer = poll - .ends_at - .filter(|_| !closed) - .map(|end| { - div() - .flex() - .items_center() - .gap(px(4.)) - .child(Icon::new(IconName::Timer).w(px(12.)).h(px(12.))) - .child(remaining(end)) - }); + let timer = poll.ends_at.filter(|_| !closed).map(|end| { + div() + .flex() + .items_center() + .gap(px(4.)) + .child(Icon::new(IconName::Timer).w(px(12.)).h(px(12.))) + .child(remaining(end)) + }); let footer = div() .flex() @@ -504,9 +500,23 @@ impl Yumush { .gap(px(2.)) .text_size(text(11.)) .text_color(palette.muted) - .child(page_button("poll_page_back", IconName::ChevronLeft, "Previous", count - 1, entity, palette)) + .child(page_button( + "poll_page_back", + IconName::ChevronLeft, + "Previous", + count - 1, + entity, + palette, + )) .child(format!("{}/{count}", page + 1)) - .child(page_button("poll_page_next", IconName::ChevronRight, "Next", 1, entity, palette)) + .child(page_button( + "poll_page_next", + IconName::ChevronRight, + "Next", + 1, + entity, + palette, + )) })) .child(icon_button( "poll_banner_jump", diff --git a/crates/client/src/gui/share_view.rs b/crates/client/src/gui/share_view.rs index 9fb5710..8ce42e4 100644 --- a/crates/client/src/gui/share_view.rs +++ b/crates/client/src/gui/share_view.rs @@ -1,11 +1,18 @@ use common::model::Id; use std::{sync::Arc, time::Duration}; -use common::share::{Codec, Fps, Kind, Resolution, Source, options}; +use common::share::{Codec, Fps, Kind, Quality, Resolution, Source, options}; + +const FULL_VOLUME: f32 = 100.; + +const TOP_QUALITY: Quality = Quality { + resolution: Resolution::P2160, + fps: Fps::F60, +}; use gpui_kit::{ - Anchor, AnyElement, AppContext, Context, Div, Entity, InteractiveElement, - IntoElement, MouseButton, ObjectFit, ParentElement, RenderImage, StatefulInteractiveElement, - Styled, StyledImage, Subscription, Task, Window, + Anchor, AnyElement, AppContext, Context, Div, Entity, InteractiveElement, IntoElement, + MouseButton, ObjectFit, ParentElement, RenderImage, StatefulInteractiveElement, Styled, + StyledImage, Subscription, Task, Window, assets::IconName, component::{ Icon, @@ -83,6 +90,7 @@ pub(super) struct Viewer { frame: Option>, pub(super) fullscreen: bool, volume: Entity, + restore: f32, _subscriptions: Vec, _tick: Task<()>, } @@ -119,6 +127,22 @@ impl Yumush { .detach(); } + fn toggle_share_mute(&mut self, window: &mut Window, cx: &mut Context) { + let current = self.settings.share.volume; + let Some(viewer) = self.chat.viewer.as_mut() else { + return; + }; + let next = if current > 0. { + viewer.restore = current; + 0. + } else { + viewer.restore + }; + let slider = viewer.volume.clone(); + slider.update(cx, |slider, cx| slider.set_value(next, window, cx)); + self.update_share(cx, |settings| settings.volume = next); + } + fn update_share(&mut self, cx: &mut Context, change: impl FnOnce(&mut ShareSettings)) { let before = self.settings.share.clone(); change(&mut self.settings.share); @@ -191,6 +215,13 @@ impl Yumush { }); } + pub(super) fn share_top(&self, user_id: Id, kind: Kind) -> Quality { + self.chat + .voice_community() + .and_then(|community_id| self.chat.share_of(community_id, user_id, kind)) + .map_or(TOP_QUALITY, |share| share.source.top) + } + pub(super) fn is_watching(&self, user_id: Id, kind: Kind) -> bool { self.chat .viewer @@ -258,6 +289,7 @@ impl Yumush { frame: None, fullscreen: false, volume, + restore: FULL_VOLUME, _subscriptions: subscriptions, _tick: tick, }); @@ -266,12 +298,13 @@ impl Yumush { let watch = WatchQuality::Auto; let volume = self.settings.share.volume; let choice = self.settings.voice.choice.clone(); + let top = self.share_top(user_id, kind); if self.chat.tiles.contains_key(&(user_id, kind)) { network.set_watch_quality(user_id, kind, watch); } else { cx.spawn_in(window, async move |this, cx| { if let Err(error) = network - .watch_share(user_id, kind, watch, volume, choice) + .watch_share(user_id, kind, watch, top, volume, choice) .await { let _ = this.update(cx, |yumush, cx| { @@ -478,10 +511,16 @@ impl Yumush { .child(name.to_string()) .child(div().flex_1()) .children(audio.then(|| { - Icon::new(IconName::Volume2) - .w(px(14.)) - .h(px(14.)) - .text_color(palette.muted) + let muted = self.settings.share.volume == 0.; + icon_button( + format!("share_mute_{muted}"), + palette, + if muted { IconName::VolumeX } else { IconName::Volume2 }, + if muted { "Unmute" } else { "Mute" }, + entity_action(entity, |yumush, window, cx| { + yumush.toggle_share_mute(window, cx) + }), + ) })) .children(audio.then(|| { div().w(px(80.)).child( diff --git a/crates/client/src/gui/sidebar.rs b/crates/client/src/gui/sidebar.rs index ff77b31..7bb43ad 100644 --- a/crates/client/src/gui/sidebar.rs +++ b/crates/client/src/gui/sidebar.rs @@ -30,7 +30,7 @@ use super::{ settings_page::{segment, segment_track}, social::Relation, voice_stats, - wave::{mini_wave_slot, wave_slot}, + wave::wave_slot, widget::{bare_input, compact_frame, icon_button}, }; @@ -237,8 +237,14 @@ impl Yumush { palette: Palette, ) -> impl IntoElement { let speaking = self.chat.waves.speaking.contains(&user.id); - let screen = self.chat.share_of(community_id, user.id, Kind::Screen).is_some(); - let camera = self.chat.share_of(community_id, user.id, Kind::Camera).is_some(); + let screen = self + .chat + .share_of(community_id, user.id, Kind::Screen) + .is_some(); + let camera = self + .chat + .share_of(community_id, user.id, Kind::Camera) + .is_some(); let user_id = user.id; let watch_screen = entity.clone(); @@ -285,47 +291,15 @@ impl Yumush { }), ); - div() + let row = div() .flex() .items_center() .gap(px(4.)) .px(px(4.)) .py(px(2.)) .rounded(px(6.)) - .when(ghost, |row| row.opacity(0.5)) .hover(move |style| style.bg(palette.hover)) .child(div().flex_1().min_w_0().child(member)) - .child( - div() - .w(px(20.)) - .h(px(20.)) - .flex_shrink_0() - .when(screen, |slot| { - slot.child( - clickable(format!("voice_screen_{user_id}"), palette, move |window, cx| { - watch_screen.update(cx, |yumush, cx| { - yumush.toggle_viewer(user_id, Kind::Screen, window, cx) - }); - }) - .tip("Watch") - .size_full() - .flex() - .items_center() - .justify_center() - .rounded(px(4.)) - .child(match self.chat.waves.share(user_id) { - Some(history) => mini_wave_slot(Some(history), 12., palette.ok) - .into_any_element(), - None => Icon::new(IconName::ScreenShare) - .w(px(12.)) - .h(px(12.)) - .text_color(palette.alert) - .into_any_element(), - }), - ) - }), - ) - .child( div() .w(px(20.)) @@ -333,11 +307,15 @@ impl Yumush { .flex_shrink_0() .when(camera, |slot| { slot.child( - clickable(format!("voice_camera_{user_id}"), palette, move |window, cx| { - watch_camera.update(cx, |yumush, cx| { - yumush.toggle_viewer(user_id, Kind::Camera, window, cx) - }); - }) + clickable( + format!("voice_camera_{user_id}"), + palette, + move |window, cx| { + watch_camera.update(cx, |yumush, cx| { + yumush.toggle_viewer(user_id, Kind::Camera, window, cx) + }); + }, + ) .tip("Watch") .size_full() .flex() @@ -353,7 +331,42 @@ impl Yumush { ) }), ) - .child(wave_slot(self.chat.waves.voice(user_id), 12., palette.ok)) + .child(wave_slot(self.chat.waves.voice(user_id), 12., palette.ok)); + + let stream = screen.then(|| { + clickable( + format!("voice_screen_{user_id}"), + palette, + move |window, cx| { + watch_screen.update(cx, |yumush, cx| { + yumush.toggle_viewer(user_id, Kind::Screen, window, cx) + }); + }, + ) + .tip("Watch") + .flex() + .items_center() + .gap(px(4.)) + .h(px(20.)) + .pl(px(28.)) + .pr(px(4.)) + .rounded(px(6.)) + .child( + Icon::new(IconName::ScreenShare) + .w(px(12.)) + .h(px(12.)) + .text_color(palette.alert), + ) + .child(div().flex_1()) + .child(wave_slot(self.chat.waves.share(user_id), 12., palette.ok)) + }); + + div() + .flex() + .flex_col() + .when(ghost, |member| member.opacity(0.5)) + .child(row) + .children(stream) } fn voice_dot(&self, entity: &Entity, palette: Palette) -> Option { diff --git a/crates/client/src/gui/wave.rs b/crates/client/src/gui/wave.rs index d0697b5..9a1d383 100644 --- a/crates/client/src/gui/wave.rs +++ b/crates/client/src/gui/wave.rs @@ -10,7 +10,6 @@ const GONE: f32 = 0.02; const AUDIBLE: f32 = 0.1; const BAR_WIDTH: f32 = 2.; const MIN_BAR: f32 = 1.5; -const MINI_GROUP: usize = 4; pub struct Wave { bars: VecDeque, @@ -91,34 +90,19 @@ impl Waves { } pub fn wave_slot(history: Option<&VecDeque>, size: f32, color: Hsla) -> Div { - slot(spectrum::BANDS, history.map(|history| history.iter().copied().collect()), size, color) -} - -pub fn mini_wave_slot(history: Option<&VecDeque>, size: f32, color: Hsla) -> Div { - let bars = history.map(|history| { - let history: Vec = history.iter().copied().collect(); - history - .chunks(MINI_GROUP) - .map(|group| group.iter().copied().fold(0., f32::max)) - .collect() - }); - slot(spectrum::BANDS / MINI_GROUP, bars, size, color) -} - -fn slot(count: usize, bars: Option>, size: f32, color: Hsla) -> Div { div() .flex_shrink_0() - .w(px(count as f32 * (BAR_WIDTH + 1.))) - .children(bars.map(|bars| wave(&bars, size, color))) + .w(px(spectrum::BANDS as f32 * (BAR_WIDTH + 1.))) + .children(history.map(|history| wave(history, size, color))) } -fn wave(bars: &[f32], size: f32, color: Hsla) -> Div { +fn wave(history: &VecDeque, size: f32, color: Hsla) -> Div { div() .flex() .items_center() .gap(px(1.)) .h(px(size)) - .children(bars.iter().map(|bar| { + .children(history.iter().map(|bar| { div() .w(px(BAR_WIDTH)) .h(px((size * bar).max(MIN_BAR))) diff --git a/crates/client/src/net/link.rs b/crates/client/src/net/link.rs index f015b6c..a32f7f1 100644 --- a/crates/client/src/net/link.rs +++ b/crates/client/src/net/link.rs @@ -80,7 +80,8 @@ impl Endpoints { } let bind: SocketAddr = bind.parse().map_err(|_| LinkError::Unreachable)?; - let mut endpoint = common::transport::endpoint(bind, None).map_err(|_| LinkError::Unreachable)?; + let mut endpoint = + common::transport::endpoint(bind, None).map_err(|_| LinkError::Unreachable)?; endpoint.set_default_client_config(config()?); *slot = Some(endpoint.clone()); diff --git a/crates/client/src/net/media.rs b/crates/client/src/net/media.rs index 45360e8..8f619f1 100644 --- a/crates/client/src/net/media.rs +++ b/crates/client/src/net/media.rs @@ -629,12 +629,13 @@ impl NetworkHandle { user_id: Id, kind: Kind, watch: WatchQuality, + top: Quality, volume: f32, choice: Choice, ) -> Result<(), Fail> { let media = self.media().clone(); let key = (user_id, kind); - let watching = Watching::new(kind, watch, volume, choice); + let watching = Watching::new(kind, watch, top, volume, choice); let quality = watching.wanted(); self.media() diff --git a/crates/client/src/share/encode.rs b/crates/client/src/share/encode.rs index 8069144..daf78f5 100644 --- a/crates/client/src/share/encode.rs +++ b/crates/client/src/share/encode.rs @@ -319,6 +319,13 @@ impl Encoders { } } + pub fn bitrate(&self) -> u32 { + self.lanes + .keys() + .map(|layer| layer.bitrate(self.source_width, self.source_height)) + .sum() + } + pub fn set_scale(&self, scale: f32) { self.scale.store(scale.to_bits(), Ordering::Relaxed); } diff --git a/crates/client/src/share/mod.rs b/crates/client/src/share/mod.rs index ab9d4de..7571ccc 100644 --- a/crates/client/src/share/mod.rs +++ b/crates/client/src/share/mod.rs @@ -16,6 +16,7 @@ pub mod encode; #[cfg(any(target_os = "linux", target_os = "windows"))] pub mod fake; pub mod frame; +pub mod pacer; pub mod reassembly; pub mod session; #[cfg(not(any(target_os = "linux", target_os = "windows")))] diff --git a/crates/client/src/share/pacer.rs b/crates/client/src/share/pacer.rs new file mode 100644 index 0000000..42fd86f --- /dev/null +++ b/crates/client/src/share/pacer.rs @@ -0,0 +1,37 @@ +use std::time::{Duration, Instant}; + +const FACTOR: f64 = 2.5; +const BURST_BYTES: f64 = 16. * 1024.; +const MIN_BYTES_PER_SECOND: f64 = 256. * 1024.; + +pub struct Pacer { + budget: f64, + at: Instant, +} + +impl Default for Pacer { + fn default() -> Self { + Self { + budget: BURST_BYTES, + at: Instant::now(), + } + } +} + +impl Pacer { + pub fn wait(&mut self, bytes: usize, bitrate: u32) { + let rate = (f64::from(bitrate) / 8. * FACTOR).max(MIN_BYTES_PER_SECOND); + let bytes = bytes as f64; + loop { + let now = Instant::now(); + self.budget = + (self.budget + now.duration_since(self.at).as_secs_f64() * rate).min(BURST_BYTES); + self.at = now; + if self.budget >= bytes { + self.budget -= bytes; + return; + } + std::thread::sleep(Duration::from_secs_f64((bytes - self.budget) / rate)); + } + } +} diff --git a/crates/client/src/share/session.rs b/crates/client/src/share/session.rs index 78a84d9..0586177 100644 --- a/crates/client/src/share/session.rs +++ b/crates/client/src/share/session.rs @@ -32,6 +32,7 @@ use super::{ congestion::{self, Controller, Uplink}, encode::{self, Encoders}, frame::{Encoded, Frame}, + pacer::Pacer, reassembly::{Assembled, Reassembler}, }; use crate::media::{ @@ -258,9 +259,9 @@ impl Sharing { }) }; let sender = { - let sent = sent.clone(); + let (sent, encoders) = (sent.clone(), encoders.clone()); Worker::spawn("share-send", move |stop| { - send(kind, encoded, connection, sent, stop) + send(kind, encoded, connection, encoders, sent, stop) }) }; @@ -371,11 +372,14 @@ fn send( kind: Kind, rx: Receiver, connection: Connection, + encoders: Arc>, sent: Arc>, stop: &AtomicBool, ) { let mut counters: HashMap = HashMap::new(); + let mut pacer = Pacer::default(); while let Some(item) = next(&rx, stop) { + let bitrate = lock(&encoders).bitrate(); lock(&sent).record(&item); let counter = counters.entry(item.layer).or_default(); let number = *counter; @@ -387,7 +391,10 @@ fn send( item.keyframe, item.timestamp_ms, &item.data, - |packet| datagram::send(&connection, Bytes::copy_from_slice(packet)), + |packet| { + pacer.wait(packet.len(), bitrate); + datagram::send(&connection, Bytes::copy_from_slice(packet)); + }, ); } } @@ -485,13 +492,21 @@ pub struct Watching { _output: Option