BlueGit

ict rusty-teams

perf(calls): 30 fps self view, 720p capture, call updates no longer re-render the whole window

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

metis Daniel Däschle · pushed by metis

Authored 2026-10-11 · 7 weeks ago

Hash
d5429c4b31c0a9be43a5d4a17ca1198d2485713b
Parent
ff739ffa
10 files changed +205 −29
crates/app/src/app_state.rs +3 −1
@@ -12,7 +12,7 @@ use teams_core::{
12 12 };
13 13
14 14 use crate::backend::{BackendEvent, ConnectionState, Engine, LiveState};
15 use crate::call::{ActiveCall, CallLauncher, MissedCall, Rings};
15 use crate::call::{ActiveCall, CallLauncher, CallMedia, MissedCall, Rings};
16 16 use calling::meeting::LiveMeeting;
17 17 use crate::card_state::{CardState, TaskDialogState};
18 18 use crate::data::{self, Directory};
@@ -114,6 +114,7 @@ pub struct AppState {
114 114 pub profiles: ProfileCache,
115 115 pub profile_request: Option<ProfileRequest>,
116 116 pub call: Option<ActiveCall>,
117 pub call_media: Option<Entity<CallMedia>>,
117 118 pub call_launcher: Option<Arc<CallLauncher>>,
118 119 pub call_count: u64,
119 120 pub call_share_sound: bool,
@@ -209,6 +210,7 @@ impl AppState {
209 210 profiles: ProfileCache::new(),
210 211 profile_request: None,
211 212 call: None,
213 call_media: None,
212 214 call_launcher: None,
213 215 call_count: 0,
214 216 call_share_sound: false,
@@ -12,7 +12,7 @@ use teams_core::{
12};
12};
13
13
14use crate::backend::{BackendEvent, ConnectionState, Engine, LiveState};
14use crate::backend::{BackendEvent, ConnectionState, Engine, LiveState};
15use crate::call::{ActiveCall, CallLauncher, MissedCall, Rings};
15use crate::call::{ActiveCall, CallLauncher, CallMedia, MissedCall, Rings};
16use calling::meeting::LiveMeeting;
16use calling::meeting::LiveMeeting;
17use crate::card_state::{CardState, TaskDialogState};
17use crate::card_state::{CardState, TaskDialogState};
18use crate::data::{self, Directory};
18use crate::data::{self, Directory};
@@ -114,6 +114,7 @@ pub struct AppState {
114 pub profiles: ProfileCache,
114 pub profiles: ProfileCache,
115 pub profile_request: Option<ProfileRequest>,
115 pub profile_request: Option<ProfileRequest>,
116 pub call: Option<ActiveCall>,
116 pub call: Option<ActiveCall>,
117 pub call_media: Option<Entity<CallMedia>>,
117 pub call_launcher: Option<Arc<CallLauncher>>,
118 pub call_launcher: Option<Arc<CallLauncher>>,
118 pub call_count: u64,
119 pub call_count: u64,
119 pub call_share_sound: bool,
120 pub call_share_sound: bool,
@@ -209,6 +210,7 @@ impl AppState {
209 profiles: ProfileCache::new(),
210 profiles: ProfileCache::new(),
210 profile_request: None,
211 profile_request: None,
211 call: None,
212 call: None,
213 call_media: None,
212 call_launcher: None,
214 call_launcher: None,
213 call_count: 0,
215 call_count: 0,
214 call_share_sound: false,
216 call_share_sound: false,
crates/app/src/call/actions.rs +38 −3
@@ -9,6 +9,7 @@ use gpui_kit::*;
9 9 use super::background::{BACKGROUND_META_KEY, BackgroundPick, SHOWN_IMAGES, is_image_file, save_custom_backgrounds};
10 10 use super::demo::{DemoCall, DemoScene, demo_caller, demo_guests, demo_ring, demo_video_ring, start_demo_call, start_demo_scene_call};
11 11 use super::features::room_closed_move;
12 use super::media::CallMedia;
12 13 use super::model::{ActiveCall, CallKind, CallModel, ended_notice};
13 14 use super::ring::{MissedCall, RingOutcome};
14 15 use super::target::{is_organizer, plan_for_chat};
@@ -191,7 +192,7 @@ impl AppState {
191 192 if ticks.is_multiple_of(SHARE_SOURCES_EVERY_TICKS) {
192 193 state.refresh_share_sources();
193 194 }
194 cx.notify();
195 CallMedia::changed(&state.call_media, cx);
195 196 }
196 197 running
197 198 });
@@ -204,13 +205,23 @@ impl AppState {
204 205 }
205 206
206 207 pub(super) fn apply_call_update(&mut self, call_id: u64, update: CallUpdate, cx: &mut Context<Self>) {
208 let media = self.call_media.clone();
207 209 let Some(call) = self.call.as_mut().filter(|call| call.id == call_id) else {
208 210 return;
209 211 };
210 212 match update {
211 213 CallUpdate::VideoReady => {
212 214 call.pictures.apply(&call.video, cx);
213 cx.notify();
215 CallMedia::changed(&media, cx);
216 return;
217 }
218 CallUpdate::Stats { .. } => return,
219 CallUpdate::Levels { local, remote } => {
220 let before = (call.model.local_speaking, call.model.remote_speaking);
221 call.model.apply(CallUpdate::Levels { local, remote });
222 if before != (call.model.local_speaking, call.model.remote_speaking) {
223 CallMedia::changed(&media, cx);
224 }
214 225 return;
215 226 }
216 227 CallUpdate::Notice(text) => {
@@ -807,7 +818,7 @@ mod tests {
807 818 use store::{ChatRecord, MemberRecord, Store};
808 819
809 820 use super::{ActiveCall, CallModel};
810 use crate::app_state::{AppState, Mode, Selection};
821 use crate::app_state::{AppEvent, AppState, Mode, Selection};
811 822 use crate::call::TransferCandidate;
812 823 use crate::call::background::BackgroundPick;
813 824 use crate::call::demo::demo_ring;
@@ -849,6 +860,30 @@ mod tests {
849 860 model
850 861 }
851 862
863 #[gpui_kit::test]
864 fn high_rate_updates_do_not_emit_call_events(cx: &mut TestAppContext) {
865 let app = app_with_call(cx);
866 let emitted = Arc::new(std::sync::atomic::AtomicUsize::new(0));
867 let counter = emitted.clone();
868 cx.update(|cx| {
869 cx.subscribe(&app, move |_, event: &AppEvent, _| {
870 if matches!(event, AppEvent::Call) {
871 counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
872 }
873 })
874 .detach();
875 app.update(cx, |state, cx| {
876 state.apply_call_update(7, CallUpdate::VideoReady, cx);
877 state.apply_call_update(7, CallUpdate::Levels { local: 0.5, remote: 0.5 }, cx);
878 state.apply_call_update(7, CallUpdate::Stats { inbound_packets: 1, outbound_packets: 1 }, cx);
879 });
880 });
881 assert_eq!(emitted.load(std::sync::atomic::Ordering::SeqCst), 0);
882 assert!(cx.update(|cx| app.read(cx).call.as_ref().unwrap().model.remote_speaking));
883 cx.update(|cx| app.update(cx, |state, cx| state.apply_call_update(7, CallUpdate::Muted(true), cx)));
884 assert_eq!(emitted.load(std::sync::atomic::Ordering::SeqCst), 1);
885 }
886
852 887 #[gpui_kit::test]
853 888 fn the_computer_sound_switch_is_remembered_and_sent_to_the_call(cx: &mut TestAppContext) {
854 889 let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
@@ -9,6 +9,7 @@ use gpui_kit::*;
9use super::background::{BACKGROUND_META_KEY, BackgroundPick, SHOWN_IMAGES, is_image_file, save_custom_backgrounds};
9use super::background::{BACKGROUND_META_KEY, BackgroundPick, SHOWN_IMAGES, is_image_file, save_custom_backgrounds};
10use super::demo::{DemoCall, DemoScene, demo_caller, demo_guests, demo_ring, demo_video_ring, start_demo_call, start_demo_scene_call};
10use super::demo::{DemoCall, DemoScene, demo_caller, demo_guests, demo_ring, demo_video_ring, start_demo_call, start_demo_scene_call};
11use super::features::room_closed_move;
11use super::features::room_closed_move;
12use super::media::CallMedia;
12use super::model::{ActiveCall, CallKind, CallModel, ended_notice};
13use super::model::{ActiveCall, CallKind, CallModel, ended_notice};
13use super::ring::{MissedCall, RingOutcome};
14use super::ring::{MissedCall, RingOutcome};
14use super::target::{is_organizer, plan_for_chat};
15use super::target::{is_organizer, plan_for_chat};
@@ -191,7 +192,7 @@ impl AppState {
191 if ticks.is_multiple_of(SHARE_SOURCES_EVERY_TICKS) {
192 if ticks.is_multiple_of(SHARE_SOURCES_EVERY_TICKS) {
192 state.refresh_share_sources();
193 state.refresh_share_sources();
193 }
194 }
194 cx.notify();
195 CallMedia::changed(&state.call_media, cx);
195 }
196 }
196 running
197 running
197 });
198 });
@@ -204,13 +205,23 @@ impl AppState {
204 }
205 }
205
206
206 pub(super) fn apply_call_update(&mut self, call_id: u64, update: CallUpdate, cx: &mut Context<Self>) {
207 pub(super) fn apply_call_update(&mut self, call_id: u64, update: CallUpdate, cx: &mut Context<Self>) {
208 let media = self.call_media.clone();
207 let Some(call) = self.call.as_mut().filter(|call| call.id == call_id) else {
209 let Some(call) = self.call.as_mut().filter(|call| call.id == call_id) else {
208 return;
210 return;
209 };
211 };
210 match update {
212 match update {
211 CallUpdate::VideoReady => {
213 CallUpdate::VideoReady => {
212 call.pictures.apply(&call.video, cx);
214 call.pictures.apply(&call.video, cx);
213 cx.notify();
215 CallMedia::changed(&media, cx);
216 return;
217 }
218 CallUpdate::Stats { .. } => return,
219 CallUpdate::Levels { local, remote } => {
220 let before = (call.model.local_speaking, call.model.remote_speaking);
221 call.model.apply(CallUpdate::Levels { local, remote });
222 if before != (call.model.local_speaking, call.model.remote_speaking) {
223 CallMedia::changed(&media, cx);
224 }
214 return;
225 return;
215 }
226 }
216 CallUpdate::Notice(text) => {
227 CallUpdate::Notice(text) => {
@@ -807,7 +818,7 @@ mod tests {
807 use store::{ChatRecord, MemberRecord, Store};
818 use store::{ChatRecord, MemberRecord, Store};
808
819
809 use super::{ActiveCall, CallModel};
820 use super::{ActiveCall, CallModel};
810 use crate::app_state::{AppState, Mode, Selection};
821 use crate::app_state::{AppEvent, AppState, Mode, Selection};
811 use crate::call::TransferCandidate;
822 use crate::call::TransferCandidate;
812 use crate::call::background::BackgroundPick;
823 use crate::call::background::BackgroundPick;
813 use crate::call::demo::demo_ring;
824 use crate::call::demo::demo_ring;
@@ -849,6 +860,30 @@ mod tests {
849 model
860 model
850 }
861 }
851
862
863 #[gpui_kit::test]
864 fn high_rate_updates_do_not_emit_call_events(cx: &mut TestAppContext) {
865 let app = app_with_call(cx);
866 let emitted = Arc::new(std::sync::atomic::AtomicUsize::new(0));
867 let counter = emitted.clone();
868 cx.update(|cx| {
869 cx.subscribe(&app, move |_, event: &AppEvent, _| {
870 if matches!(event, AppEvent::Call) {
871 counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
872 }
873 })
874 .detach();
875 app.update(cx, |state, cx| {
876 state.apply_call_update(7, CallUpdate::VideoReady, cx);
877 state.apply_call_update(7, CallUpdate::Levels { local: 0.5, remote: 0.5 }, cx);
878 state.apply_call_update(7, CallUpdate::Stats { inbound_packets: 1, outbound_packets: 1 }, cx);
879 });
880 });
881 assert_eq!(emitted.load(std::sync::atomic::Ordering::SeqCst), 0);
882 assert!(cx.update(|cx| app.read(cx).call.as_ref().unwrap().model.remote_speaking));
883 cx.update(|cx| app.update(cx, |state, cx| state.apply_call_update(7, CallUpdate::Muted(true), cx)));
884 assert_eq!(emitted.load(std::sync::atomic::Ordering::SeqCst), 1);
885 }
886
852 #[gpui_kit::test]
887 #[gpui_kit::test]
853 fn the_computer_sound_switch_is_remembered_and_sent_to_the_call(cx: &mut TestAppContext) {
888 fn the_computer_sound_switch_is_remembered_and_sent_to_the_call(cx: &mut TestAppContext) {
854 let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
889 let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
crates/app/src/call/media.rs added +11 −0
@@ -0,0 +1,11 @@
1 use gpui_kit::*;
2
3 pub struct CallMedia;
4
5 impl CallMedia {
6 pub fn changed(media: &Option<Entity<CallMedia>>, cx: &mut App) {
7 if let Some(media) = media {
8 media.update(cx, |_, cx| cx.notify());
9 }
10 }
11 }
@@ -0,0 +1,11 @@
1use gpui_kit::*;
2
3pub struct CallMedia;
4
5impl CallMedia {
6 pub fn changed(media: &Option<Entity<CallMedia>>, cx: &mut App) {
7 if let Some(media) = media {
8 media.update(cx, |_, cx| cx.notify());
9 }
10 }
11}
crates/app/src/call/mod.rs +2 −0
@@ -6,6 +6,7 @@ mod features;
6 6 mod history;
7 7 mod join;
8 8 mod launcher;
9 mod media;
9 10 mod model;
10 11 mod pictures;
11 12 mod ring;
@@ -17,6 +18,7 @@ pub use features::TransferCandidate;
17 18 pub use demo::DemoScene;
18 19 pub use history::{CallRow, call_rows};
19 20 pub use launcher::CallLauncher;
21 pub use media::CallMedia;
20 22 pub use model::{
21 23 ActiveCall, CAPTION_SHOWN, CHAT_OPEN_TILES, CallKind, CallModel, Focus, GridLayout, MAX_TILES, REACTION_SHOWN, Tile, TileSize, TileState,
22 24 grid_layout, tile_size,
@@ -6,6 +6,7 @@ mod features;
6mod history;
6mod history;
7mod join;
7mod join;
8mod launcher;
8mod launcher;
9mod media;
9mod model;
10mod model;
10mod pictures;
11mod pictures;
11mod ring;
12mod ring;
@@ -17,6 +18,7 @@ pub use features::TransferCandidate;
17pub use demo::DemoScene;
18pub use demo::DemoScene;
18pub use history::{CallRow, call_rows};
19pub use history::{CallRow, call_rows};
19pub use launcher::CallLauncher;
20pub use launcher::CallLauncher;
21pub use media::CallMedia;
20pub use model::{
22pub use model::{
21 ActiveCall, CAPTION_SHOWN, CHAT_OPEN_TILES, CallKind, CallModel, Focus, GridLayout, MAX_TILES, REACTION_SHOWN, Tile, TileSize, TileState,
23 ActiveCall, CAPTION_SHOWN, CHAT_OPEN_TILES, CallKind, CallModel, Focus, GridLayout, MAX_TILES, REACTION_SHOWN, Tile, TileSize, TileState,
22 grid_layout, tile_size,
24 grid_layout, tile_size,
crates/app/src/views/call_view.rs +10 −3
@@ -1,5 +1,5 @@
1 1 use std::sync::Arc;
2 use std::time::{Duration, Instant};
2 use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
3 3
4 4 use calling::{DeviceEntry, Reaction, VideoKey};
5 5 use gpui_kit::assets::IconName;
@@ -35,6 +35,8 @@ pub(super) const CONTROL_SIZE: f32 = 44.;
35 35 const CONTROL_ICON: f32 = 20.;
36 36 pub(super) const MENU_WIDTH: f32 = 280.;
37 37 const PULSE_PERIOD: Duration = Duration::from_millis(1400);
38 const BLINK_HALF_PERIOD: Duration = Duration::from_millis(500);
39 const BLINK_DIMMED_OPACITY: f32 = 0.45;
38 40 const DISABLED_OPACITY: f32 = 0.4;
39 41 const TILE_GAP: f32 = 20.;
40 42 const GRID_PADDING: f32 = 24.;
@@ -159,6 +161,11 @@ pub fn pulsing(element: impl IntoElement + 'static, id: &'static str) -> AnyElem
159 161 .into_any_element()
160 162 }
161 163
164 fn blinking(element: impl IntoElement + 'static) -> AnyElement {
165 let dimmed = SystemTime::now().duration_since(UNIX_EPOCH).is_ok_and(|elapsed| (elapsed.as_millis() / BLINK_HALF_PERIOD.as_millis()) % 2 == 1);
166 div().child(element).opacity(if dimmed { BLINK_DIMMED_OPACITY } else { 1. }).into_any_element()
167 }
168
162 169 fn speaking_ring(avatar: AnyElement, speaking: bool) -> Div {
163 170 div()
164 171 .p(px(RING_GAP))
@@ -707,10 +714,10 @@ fn person_tile_body(state: &AppState, model: &CallModel, remote: &Tile, size: Ti
707 714 }
708 715 let waiting = remote.state == TileState::Invited;
709 716 let avatar = person_avatar(&state.directory, remote.user_id.as_deref(), &remote.name, size.avatar);
710 let avatar = if waiting { pulsing(avatar, "call-invited-pulse") } else { avatar };
717 let avatar = if waiting { blinking(avatar) } else { avatar };
711 718 let caption = model.tile_caption(remote).map(|text| {
712 719 let label = div().text_size(px(12.)).text_color(theme::text_muted()).child(text);
713 if waiting { pulsing(label, "call-invited-caption") } else { label.into_any_element() }
720 if waiting { blinking(label) } else { label.into_any_element() }
714 721 });
715 722 tile(size, avatar, &remote.name, model.tile_speaking(remote), remote.muted, caption, extras).into_any_element()
716 723 }
@@ -1,5 +1,5 @@
1use std::sync::Arc;
1use std::sync::Arc;
2use std::time::{Duration, Instant};
2use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
3
3
4use calling::{DeviceEntry, Reaction, VideoKey};
4use calling::{DeviceEntry, Reaction, VideoKey};
5use gpui_kit::assets::IconName;
5use gpui_kit::assets::IconName;
@@ -35,6 +35,8 @@ pub(super) const CONTROL_SIZE: f32 = 44.;
35const CONTROL_ICON: f32 = 20.;
35const CONTROL_ICON: f32 = 20.;
36pub(super) const MENU_WIDTH: f32 = 280.;
36pub(super) const MENU_WIDTH: f32 = 280.;
37const PULSE_PERIOD: Duration = Duration::from_millis(1400);
37const PULSE_PERIOD: Duration = Duration::from_millis(1400);
38const BLINK_HALF_PERIOD: Duration = Duration::from_millis(500);
39const BLINK_DIMMED_OPACITY: f32 = 0.45;
38const DISABLED_OPACITY: f32 = 0.4;
40const DISABLED_OPACITY: f32 = 0.4;
39const TILE_GAP: f32 = 20.;
41const TILE_GAP: f32 = 20.;
40const GRID_PADDING: f32 = 24.;
42const GRID_PADDING: f32 = 24.;
@@ -159,6 +161,11 @@ pub fn pulsing(element: impl IntoElement + 'static, id: &'static str) -> AnyElem
159 .into_any_element()
161 .into_any_element()
160}
162}
161
163
164fn blinking(element: impl IntoElement + 'static) -> AnyElement {
165 let dimmed = SystemTime::now().duration_since(UNIX_EPOCH).is_ok_and(|elapsed| (elapsed.as_millis() / BLINK_HALF_PERIOD.as_millis()) % 2 == 1);
166 div().child(element).opacity(if dimmed { BLINK_DIMMED_OPACITY } else { 1. }).into_any_element()
167}
168
162fn speaking_ring(avatar: AnyElement, speaking: bool) -> Div {
169fn speaking_ring(avatar: AnyElement, speaking: bool) -> Div {
163 div()
170 div()
164 .p(px(RING_GAP))
171 .p(px(RING_GAP))
@@ -707,10 +714,10 @@ fn person_tile_body(state: &AppState, model: &CallModel, remote: &Tile, size: Ti
707 }
714 }
708 let waiting = remote.state == TileState::Invited;
715 let waiting = remote.state == TileState::Invited;
709 let avatar = person_avatar(&state.directory, remote.user_id.as_deref(), &remote.name, size.avatar);
716 let avatar = person_avatar(&state.directory, remote.user_id.as_deref(), &remote.name, size.avatar);
710 let avatar = if waiting { pulsing(avatar, "call-invited-pulse") } else { avatar };
717 let avatar = if waiting { blinking(avatar) } else { avatar };
711 let caption = model.tile_caption(remote).map(|text| {
718 let caption = model.tile_caption(remote).map(|text| {
712 let label = div().text_size(px(12.)).text_color(theme::text_muted()).child(text);
719 let label = div().text_size(px(12.)).text_color(theme::text_muted()).child(text);
713 if waiting { pulsing(label, "call-invited-caption") } else { label.into_any_element() }
720 if waiting { blinking(label) } else { label.into_any_element() }
714 });
721 });
715 tile(size, avatar, &remote.name, model.tile_speaking(remote), remote.muted, caption, extras).into_any_element()
722 tile(size, avatar, &remote.name, model.tile_speaking(remote), remote.muted, caption, extras).into_any_element()
716}
723}
crates/app/src/views/conversation.rs +1 −0
@@ -405,6 +405,7 @@ impl ConversationView {
405 405 let draft = cx.new(|cx| NewChatDraft::new(app.clone(), window, cx));
406 406 let subscriptions = vec![
407 407 cx.subscribe_in(&app, window, Self::on_app_event),
408 cx.observe(&app, |_, _, cx| cx.notify()),
408 409 cx.subscribe_in(&composer, window, Self::on_composer_event),
409 410 cx.subscribe_in(&draft, window, Self::on_draft_event),
410 411 cx.subscribe_in(&subject, window, Self::on_subject_event),
@@ -405,6 +405,7 @@ impl ConversationView {
405 let draft = cx.new(|cx| NewChatDraft::new(app.clone(), window, cx));
405 let draft = cx.new(|cx| NewChatDraft::new(app.clone(), window, cx));
406 let subscriptions = vec![
406 let subscriptions = vec![
407 cx.subscribe_in(&app, window, Self::on_app_event),
407 cx.subscribe_in(&app, window, Self::on_app_event),
408 cx.observe(&app, |_, _, cx| cx.notify()),
408 cx.subscribe_in(&composer, window, Self::on_composer_event),
409 cx.subscribe_in(&composer, window, Self::on_composer_event),
409 cx.subscribe_in(&draft, window, Self::on_draft_event),
410 cx.subscribe_in(&draft, window, Self::on_draft_event),
410 cx.subscribe_in(&subject, window, Self::on_subject_event),
411 cx.subscribe_in(&subject, window, Self::on_subject_event),
crates/app/src/views/shell.rs +13 −3
@@ -16,7 +16,7 @@ use super::shortcuts::{
16 16 ToggleCallShare,
17 17 };
18 18 use super::shortcuts_dialog::{ShortcutsDialog, ShortcutsDialogEvent};
19 use super::sidebar::SidebarView;
19 use super::sidebar::{SIDEBAR_WIDTH, SidebarView};
20 20 use super::status_bar::render_status_bar;
21 21 use super::status_menu::own_status_button;
22 22 use super::status_message_dialog::{StatusMessageDialog, StatusMessageDialogEvent};
@@ -24,6 +24,7 @@ use super::switcher::{Switcher, SwitcherEvent, candidates_from};
24 24 use super::title_bar::render_title_bar;
25 25 use crate::activity::ActivityCenter;
26 26 use crate::app_state::{AppEvent, AppState, Selection};
27 use crate::call::CallMedia;
27 28 use crate::embedded_web::{Overlays, RootFocus};
28 29 use crate::notice::NoticeAction;
29 30 use crate::notify::{NotificationCenter, selection_for};
@@ -69,6 +70,7 @@ pub struct AppShell {
69 70 open_target: Option<OpenTarget>,
70 71 update: UpdateStatus,
71 72 _subscription: Subscription,
73 _call_media_observation: Subscription,
72 74 _activity_observation: Subscription,
73 75 _escape_observation: Subscription,
74 76 }
@@ -94,6 +96,9 @@ impl AppShell {
94 96 window: &mut Window,
95 97 cx: &mut Context<Self>,
96 98 ) -> Self {
99 let call_media = cx.new(|_| CallMedia);
100 state.update(cx, |state, _| state.call_media = Some(call_media.clone()));
101 let call_media_observation = cx.observe(&call_media, |_, _, cx| cx.notify());
97 102 let sidebar = cx.new(|cx| SidebarView::new(state.clone(), cx));
98 103 let conversation = cx.new(|cx| ConversationView::new(state.clone(), window, cx));
99 104 let subscription =
@@ -147,6 +152,7 @@ impl AppShell {
147 152 open_target,
148 153 update: UpdateStatus::UpToDate,
149 154 _subscription: subscription,
155 _call_media_observation: call_media_observation,
150 156 _activity_observation: activity_observation,
151 157 _escape_observation: escape_observation,
152 158 };
@@ -625,10 +631,14 @@ impl Render for AppShell {
625 631 .flex_1()
626 632 .min_h_0()
627 633 .w_full()
628 .child(self.sidebar.clone())
634 .child(self.sidebar.clone().cached(StyleRefinement::default().w(px(SIDEBAR_WIDTH)).h_full().flex_none()))
629 635 .child(match call_view {
630 636 Some(call_view) => call_view,
631 None => self.conversation.clone().into_any_element(),
637 None => self
638 .conversation
639 .clone()
640 .cached(StyleRefinement::default().flex_1().min_w_0().h_full())
641 .into_any_element(),
632 642 }),
633 643 )
634 644 .child(status),
@@ -16,7 +16,7 @@ use super::shortcuts::{
16 ToggleCallShare,
16 ToggleCallShare,
17};
17};
18use super::shortcuts_dialog::{ShortcutsDialog, ShortcutsDialogEvent};
18use super::shortcuts_dialog::{ShortcutsDialog, ShortcutsDialogEvent};
19use super::sidebar::SidebarView;
19use super::sidebar::{SIDEBAR_WIDTH, SidebarView};
20use super::status_bar::render_status_bar;
20use super::status_bar::render_status_bar;
21use super::status_menu::own_status_button;
21use super::status_menu::own_status_button;
22use super::status_message_dialog::{StatusMessageDialog, StatusMessageDialogEvent};
22use super::status_message_dialog::{StatusMessageDialog, StatusMessageDialogEvent};
@@ -24,6 +24,7 @@ use super::switcher::{Switcher, SwitcherEvent, candidates_from};
24use super::title_bar::render_title_bar;
24use super::title_bar::render_title_bar;
25use crate::activity::ActivityCenter;
25use crate::activity::ActivityCenter;
26use crate::app_state::{AppEvent, AppState, Selection};
26use crate::app_state::{AppEvent, AppState, Selection};
27use crate::call::CallMedia;
27use crate::embedded_web::{Overlays, RootFocus};
28use crate::embedded_web::{Overlays, RootFocus};
28use crate::notice::NoticeAction;
29use crate::notice::NoticeAction;
29use crate::notify::{NotificationCenter, selection_for};
30use crate::notify::{NotificationCenter, selection_for};
@@ -69,6 +70,7 @@ pub struct AppShell {
69 open_target: Option<OpenTarget>,
70 open_target: Option<OpenTarget>,
70 update: UpdateStatus,
71 update: UpdateStatus,
71 _subscription: Subscription,
72 _subscription: Subscription,
73 _call_media_observation: Subscription,
72 _activity_observation: Subscription,
74 _activity_observation: Subscription,
73 _escape_observation: Subscription,
75 _escape_observation: Subscription,
74}
76}
@@ -94,6 +96,9 @@ impl AppShell {
94 window: &mut Window,
96 window: &mut Window,
95 cx: &mut Context<Self>,
97 cx: &mut Context<Self>,
96 ) -> Self {
98 ) -> Self {
99 let call_media = cx.new(|_| CallMedia);
100 state.update(cx, |state, _| state.call_media = Some(call_media.clone()));
101 let call_media_observation = cx.observe(&call_media, |_, _, cx| cx.notify());
97 let sidebar = cx.new(|cx| SidebarView::new(state.clone(), cx));
102 let sidebar = cx.new(|cx| SidebarView::new(state.clone(), cx));
98 let conversation = cx.new(|cx| ConversationView::new(state.clone(), window, cx));
103 let conversation = cx.new(|cx| ConversationView::new(state.clone(), window, cx));
99 let subscription =
104 let subscription =
@@ -147,6 +152,7 @@ impl AppShell {
147 open_target,
152 open_target,
148 update: UpdateStatus::UpToDate,
153 update: UpdateStatus::UpToDate,
149 _subscription: subscription,
154 _subscription: subscription,
155 _call_media_observation: call_media_observation,
150 _activity_observation: activity_observation,
156 _activity_observation: activity_observation,
151 _escape_observation: escape_observation,
157 _escape_observation: escape_observation,
152 };
158 };
@@ -625,10 +631,14 @@ impl Render for AppShell {
625 .flex_1()
631 .flex_1()
626 .min_h_0()
632 .min_h_0()
627 .w_full()
633 .w_full()
628 .child(self.sidebar.clone())
634 .child(self.sidebar.clone().cached(StyleRefinement::default().w(px(SIDEBAR_WIDTH)).h_full().flex_none()))
629 .child(match call_view {
635 .child(match call_view {
630 Some(call_view) => call_view,
636 Some(call_view) => call_view,
631 None => self.conversation.clone().into_any_element(),
637 None => self
638 .conversation
639 .clone()
640 .cached(StyleRefinement::default().flex_1().min_w_0().h_full())
641 .into_any_element(),
632 }),
642 }),
633 )
643 )
634 .child(status),
644 .child(status),
crates/app/src/views/sidebar.rs +3 −0
@@ -272,6 +272,7 @@ pub struct SidebarView {
272 272 channels_scroll: ScrollHandle,
273 273 calls_scroll: ScrollHandle,
274 274 _subscription: Subscription,
275 _state_observation: Subscription,
275 276 }
276 277
277 278 fn preview_text(preview: &Preview) -> Option<(String, bool)> {
@@ -342,6 +343,7 @@ impl SidebarView {
342 343 cx.notify();
343 344 }
344 345 });
346 let state_observation = cx.observe(&state, |_, _, cx| cx.notify());
345 347 let tab = if state.read(cx).start_on_channels {
346 348 SidebarTab::Channels
347 349 } else {
@@ -358,6 +360,7 @@ impl SidebarView {
358 360 channels_scroll: ScrollHandle::new(),
359 361 calls_scroll: ScrollHandle::new(),
360 362 _subscription: subscription,
363 _state_observation: state_observation,
361 364 }
362 365 }
363 366
@@ -272,6 +272,7 @@ pub struct SidebarView {
272 channels_scroll: ScrollHandle,
272 channels_scroll: ScrollHandle,
273 calls_scroll: ScrollHandle,
273 calls_scroll: ScrollHandle,
274 _subscription: Subscription,
274 _subscription: Subscription,
275 _state_observation: Subscription,
275}
276}
276
277
277fn preview_text(preview: &Preview) -> Option<(String, bool)> {
278fn preview_text(preview: &Preview) -> Option<(String, bool)> {
@@ -342,6 +343,7 @@ impl SidebarView {
342 cx.notify();
343 cx.notify();
343 }
344 }
344 });
345 });
346 let state_observation = cx.observe(&state, |_, _, cx| cx.notify());
345 let tab = if state.read(cx).start_on_channels {
347 let tab = if state.read(cx).start_on_channels {
346 SidebarTab::Channels
348 SidebarTab::Channels
347 } else {
349 } else {
@@ -358,6 +360,7 @@ impl SidebarView {
358 channels_scroll: ScrollHandle::new(),
360 channels_scroll: ScrollHandle::new(),
359 calls_scroll: ScrollHandle::new(),
361 calls_scroll: ScrollHandle::new(),
360 _subscription: subscription,
362 _subscription: subscription,
363 _state_observation: state_observation,
361 }
364 }
362 }
365 }
363
366
crates/calling/src/camera.rs +118 −11
@@ -1,10 +1,10 @@
1 1 use std::sync::Arc;
2 2 use std::time::Duration;
3 3
4 use libwebrtc::native::yuv_helper::abgr_to_i420;
4 use libwebrtc::native::yuv_helper::{abgr_to_i420, nv12_to_i420};
5 5 use libwebrtc::video_frame::I420Buffer;
6 6 use nokhwa::pixel_format::RgbAFormat;
7 use nokhwa::utils::{ApiBackend, CameraIndex, RequestedFormat, RequestedFormatType};
7 use nokhwa::utils::{ApiBackend, CameraFormat, CameraIndex, FrameFormat, RequestedFormat, RequestedFormatType, Resolution};
8 8 use nokhwa::{Camera, query};
9 9 use std::sync::atomic::Ordering;
10 10
@@ -15,6 +15,10 @@ use crate::error::{Error, Result};
15 15
16 16 const RETRY_PAUSE: Duration = Duration::from_millis(20);
17 17 const BYTES_PER_PIXEL: u32 = 4;
18 const CAPTURE_WIDTH: u32 = 1280;
19 const CAPTURE_HEIGHT: u32 = 720;
20 const CAPTURE_FPS: u32 = 30;
21 const DIRECT_FORMATS: [FrameFormat; 2] = [FrameFormat::NV12, FrameFormat::YUYV];
18 22
19 23 #[derive(Debug, Clone, PartialEq, Eq)]
20 24 pub struct CameraDevice {
@@ -62,6 +66,76 @@ pub(crate) fn i420_from_rgba(rgba: &[u8], width: u32, height: u32) -> I420Buffer
62 66 buffer
63 67 }
64 68
69 fn open_camera(index: CameraIndex) -> std::result::Result<Camera, nokhwa::NokhwaError> {
70 let wanted = Resolution::new(CAPTURE_WIDTH, CAPTURE_HEIGHT);
71 let mut requests: Vec<RequestedFormatType> = DIRECT_FORMATS
72 .into_iter()
73 .map(|frame_format| RequestedFormatType::Closest(CameraFormat::new(wanted, frame_format, CAPTURE_FPS)))
74 .collect();
75 requests.push(RequestedFormatType::AbsoluteHighestFrameRate);
76 let mut last_error = None;
77 for request in requests {
78 let format = RequestedFormat::new::<RgbAFormat>(request);
79 match Camera::new(index.clone(), format).and_then(|mut camera| camera.open_stream().map(|()| camera)) {
80 Ok(camera) => return Ok(camera),
81 Err(error) => last_error = Some(error),
82 }
83 }
84 Err(last_error.expect("at least one request"))
85 }
86
87 pub(crate) fn i420_from_nv12(data: &[u8], width: u32, height: u32) -> Option<I420Buffer> {
88 let luma_len = width as usize * height as usize;
89 if data.len() < luma_len + luma_len / 2 {
90 return None;
91 }
92 let mut buffer = I420Buffer::new(width, height);
93 let (stride_y, stride_u, stride_v) = buffer.strides();
94 let (plane_y, plane_u, plane_v) = buffer.data_mut();
95 let (source_y, source_uv) = data.split_at(luma_len);
96 nv12_to_i420(source_y, width, source_uv, width, plane_y, stride_y, plane_u, stride_u, plane_v, stride_v, width as i32, height as i32);
97 Some(buffer)
98 }
99
100 pub(crate) fn i420_from_yuyv(data: &[u8], width: u32, height: u32) -> Option<I420Buffer> {
101 let (width_pixels, height_rows) = (width as usize, height as usize);
102 let row_bytes = width_pixels * 2;
103 if data.len() < row_bytes * height_rows {
104 return None;
105 }
106 let mut buffer = I420Buffer::new(width, height);
107 let (stride_y, stride_u, stride_v) = buffer.strides();
108 let (plane_y, plane_u, plane_v) = buffer.data_mut();
109 for row in 0..height_rows {
110 let source = &data[row * row_bytes..(row + 1) * row_bytes];
111 let luma_row = &mut plane_y[row * stride_y as usize..][..width_pixels];
112 for (luma, pair) in luma_row.chunks_exact_mut(2).zip(source.chunks_exact(4)) {
113 luma[0] = pair[0];
114 luma[1] = pair[2];
115 }
116 }
117 for row in 0..height_rows / 2 {
118 let upper = &data[row * 2 * row_bytes..][..row_bytes];
119 let lower = &data[(row * 2 + 1) * row_bytes..][..row_bytes];
120 let blue_row = &mut plane_u[row * stride_u as usize..][..width_pixels / 2];
121 let red_row = &mut plane_v[row * stride_v as usize..][..width_pixels / 2];
122 for (column, (blue, red)) in blue_row.iter_mut().zip(red_row.iter_mut()).enumerate() {
123 let offset = column * 4;
124 *blue = ((u16::from(upper[offset + 1]) + u16::from(lower[offset + 1]) + 1) / 2) as u8;
125 *red = ((u16::from(upper[offset + 3]) + u16::from(lower[offset + 3]) + 1) / 2) as u8;
126 }
127 }
128 Some(buffer)
129 }
130
131 fn direct_i420(frame_format: FrameFormat, data: &[u8], width: u32, height: u32) -> Option<I420Buffer> {
132 match frame_format {
133 FrameFormat::NV12 => i420_from_nv12(data, width, height),
134 FrameFormat::YUYV => i420_from_yuyv(data, width, height),
135 _ => None,
136 }
137 }
138
65 139 pub fn start_camera(
66 140 choice: &DeviceChoice,
67 141 blur: Arc<BlurSettings>,
@@ -70,24 +144,37 @@ pub fn start_camera(
70 144 ) -> Result<Capture> {
71 145 let index = camera_index(choice);
72 146 Capture::spawn_thread("camera", move |stop| {
73 let format = RequestedFormat::new::<RgbAFormat>(RequestedFormatType::AbsoluteHighestFrameRate);
74 let mut camera = match Camera::new(index, format).and_then(|mut camera| camera.open_stream().map(|()| camera)) {
147 let mut camera = match open_camera(index) {
75 148 Ok(camera) => camera,
76 149 Err(error) => return failed(error.to_string()),
77 150 };
78 let mut blur_stage = BlurStage::new(blur);
151 let mut blur_stage = BlurStage::new(blur.clone());
152 let mut warned_undecodable = false;
79 153 while !stop.load(Ordering::SeqCst) {
80 154 let Ok(frame) = camera.frame() else {
81 155 std::thread::sleep(RETRY_PAUSE);
82 156 continue;
83 157 };
84 let Ok(decoded) = frame.decode_image::<RgbAFormat>() else { continue };
85 let (width, height) = (decoded.width(), decoded.height());
86 if width >= 2 && height >= 2 && width % 2 == 0 && height % 2 == 0 {
87 let mut rgba = decoded.into_raw();
88 blur_stage.apply_rgba(&mut rgba, width as usize, height as usize);
89 deliver(i420_from_rgba(&rgba, width, height));
158 let resolution = frame.resolution();
159 let (width, height) = (resolution.width(), resolution.height());
160 if width < 2 || height < 2 || width % 2 != 0 || height % 2 != 0 {
161 continue;
162 }
163 if !blur.enabled()
164 && let Some(buffer) = direct_i420(frame.source_frame_format(), frame.buffer(), width, height)
165 {
166 deliver(buffer);
167 continue;
90 168 }
169 let Ok(decoded) = frame.decode_image::<RgbAFormat>() else {
170 if !std::mem::replace(&mut warned_undecodable, true) {
171 eprintln!("calls: camera delivers {} and no decoder is available", frame.source_frame_format());
172 }
173 continue;
174 };
175 let mut rgba = decoded.into_raw();
176 blur_stage.apply_rgba(&mut rgba, width as usize, height as usize);
177 deliver(i420_from_rgba(&rgba, width, height));
91 178 }
92 179 let _ = camera.stop_stream();
93 180 })
@@ -127,6 +214,26 @@ mod tests {
127 214 assert_eq!(entries[1].choice, DeviceChoice::Device("0".into()));
128 215 }
129 216
217 #[test]
218 fn yuyv_converts_to_i420_with_averaged_chroma() {
219 let row_a = [10u8, 100, 20, 200, 30, 50, 40, 60];
220 let row_b = [11u8, 120, 21, 220, 31, 70, 41, 80];
221 let data: Vec<u8> = row_a.iter().chain(row_b.iter()).copied().collect();
222 let mut buffer = i420_from_yuyv(&data, 4, 2).expect("converted");
223 let (plane_y, plane_u, plane_v) = buffer.data_mut();
224 assert_eq!(&plane_y[..4], &[10, 20, 30, 40]);
225 assert_eq!(plane_u[0], 110);
226 assert_eq!(plane_u[1], 60);
227 assert_eq!(plane_v[0], 210);
228 assert_eq!(plane_v[1], 70);
229 }
230
231 #[test]
232 fn short_raw_frames_are_rejected() {
233 assert!(i420_from_yuyv(&[0; 8], 4, 2).is_none());
234 assert!(i420_from_nv12(&[0; 8], 4, 2).is_none());
235 }
236
130 237 #[test]
131 238 fn camera_choices_map_to_indices_or_names() {
132 239 assert!(matches!(camera_index(&DeviceChoice::SystemDefault), CameraIndex::Index(0)));
@@ -1,10 +1,10 @@
1use std::sync::Arc;
1use std::sync::Arc;
2use std::time::Duration;
2use std::time::Duration;
3
3
4use libwebrtc::native::yuv_helper::abgr_to_i420;
4use libwebrtc::native::yuv_helper::{abgr_to_i420, nv12_to_i420};
5use libwebrtc::video_frame::I420Buffer;
5use libwebrtc::video_frame::I420Buffer;
6use nokhwa::pixel_format::RgbAFormat;
6use nokhwa::pixel_format::RgbAFormat;
7use nokhwa::utils::{ApiBackend, CameraIndex, RequestedFormat, RequestedFormatType};
7use nokhwa::utils::{ApiBackend, CameraFormat, CameraIndex, FrameFormat, RequestedFormat, RequestedFormatType, Resolution};
8use nokhwa::{Camera, query};
8use nokhwa::{Camera, query};
9use std::sync::atomic::Ordering;
9use std::sync::atomic::Ordering;
10
10
@@ -15,6 +15,10 @@ use crate::error::{Error, Result};
15
15
16const RETRY_PAUSE: Duration = Duration::from_millis(20);
16const RETRY_PAUSE: Duration = Duration::from_millis(20);
17const BYTES_PER_PIXEL: u32 = 4;
17const BYTES_PER_PIXEL: u32 = 4;
18const CAPTURE_WIDTH: u32 = 1280;
19const CAPTURE_HEIGHT: u32 = 720;
20const CAPTURE_FPS: u32 = 30;
21const DIRECT_FORMATS: [FrameFormat; 2] = [FrameFormat::NV12, FrameFormat::YUYV];
18
22
19#[derive(Debug, Clone, PartialEq, Eq)]
23#[derive(Debug, Clone, PartialEq, Eq)]
20pub struct CameraDevice {
24pub struct CameraDevice {
@@ -62,6 +66,76 @@ pub(crate) fn i420_from_rgba(rgba: &[u8], width: u32, height: u32) -> I420Buffer
62 buffer
66 buffer
63}
67}
64
68
69fn open_camera(index: CameraIndex) -> std::result::Result<Camera, nokhwa::NokhwaError> {
70 let wanted = Resolution::new(CAPTURE_WIDTH, CAPTURE_HEIGHT);
71 let mut requests: Vec<RequestedFormatType> = DIRECT_FORMATS
72 .into_iter()
73 .map(|frame_format| RequestedFormatType::Closest(CameraFormat::new(wanted, frame_format, CAPTURE_FPS)))
74 .collect();
75 requests.push(RequestedFormatType::AbsoluteHighestFrameRate);
76 let mut last_error = None;
77 for request in requests {
78 let format = RequestedFormat::new::<RgbAFormat>(request);
79 match Camera::new(index.clone(), format).and_then(|mut camera| camera.open_stream().map(|()| camera)) {
80 Ok(camera) => return Ok(camera),
81 Err(error) => last_error = Some(error),
82 }
83 }
84 Err(last_error.expect("at least one request"))
85}
86
87pub(crate) fn i420_from_nv12(data: &[u8], width: u32, height: u32) -> Option<I420Buffer> {
88 let luma_len = width as usize * height as usize;
89 if data.len() < luma_len + luma_len / 2 {
90 return None;
91 }
92 let mut buffer = I420Buffer::new(width, height);
93 let (stride_y, stride_u, stride_v) = buffer.strides();
94 let (plane_y, plane_u, plane_v) = buffer.data_mut();
95 let (source_y, source_uv) = data.split_at(luma_len);
96 nv12_to_i420(source_y, width, source_uv, width, plane_y, stride_y, plane_u, stride_u, plane_v, stride_v, width as i32, height as i32);
97 Some(buffer)
98}
99
100pub(crate) fn i420_from_yuyv(data: &[u8], width: u32, height: u32) -> Option<I420Buffer> {
101 let (width_pixels, height_rows) = (width as usize, height as usize);
102 let row_bytes = width_pixels * 2;
103 if data.len() < row_bytes * height_rows {
104 return None;
105 }
106 let mut buffer = I420Buffer::new(width, height);
107 let (stride_y, stride_u, stride_v) = buffer.strides();
108 let (plane_y, plane_u, plane_v) = buffer.data_mut();
109 for row in 0..height_rows {
110 let source = &data[row * row_bytes..(row + 1) * row_bytes];
111 let luma_row = &mut plane_y[row * stride_y as usize..][..width_pixels];
112 for (luma, pair) in luma_row.chunks_exact_mut(2).zip(source.chunks_exact(4)) {
113 luma[0] = pair[0];
114 luma[1] = pair[2];
115 }
116 }
117 for row in 0..height_rows / 2 {
118 let upper = &data[row * 2 * row_bytes..][..row_bytes];
119 let lower = &data[(row * 2 + 1) * row_bytes..][..row_bytes];
120 let blue_row = &mut plane_u[row * stride_u as usize..][..width_pixels / 2];
121 let red_row = &mut plane_v[row * stride_v as usize..][..width_pixels / 2];
122 for (column, (blue, red)) in blue_row.iter_mut().zip(red_row.iter_mut()).enumerate() {
123 let offset = column * 4;
124 *blue = ((u16::from(upper[offset + 1]) + u16::from(lower[offset + 1]) + 1) / 2) as u8;
125 *red = ((u16::from(upper[offset + 3]) + u16::from(lower[offset + 3]) + 1) / 2) as u8;
126 }
127 }
128 Some(buffer)
129}
130
131fn direct_i420(frame_format: FrameFormat, data: &[u8], width: u32, height: u32) -> Option<I420Buffer> {
132 match frame_format {
133 FrameFormat::NV12 => i420_from_nv12(data, width, height),
134 FrameFormat::YUYV => i420_from_yuyv(data, width, height),
135 _ => None,
136 }
137}
138
65pub fn start_camera(
139pub fn start_camera(
66 choice: &DeviceChoice,
140 choice: &DeviceChoice,
67 blur: Arc<BlurSettings>,
141 blur: Arc<BlurSettings>,
@@ -70,24 +144,37 @@ pub fn start_camera(
70) -> Result<Capture> {
144) -> Result<Capture> {
71 let index = camera_index(choice);
145 let index = camera_index(choice);
72 Capture::spawn_thread("camera", move |stop| {
146 Capture::spawn_thread("camera", move |stop| {
73 let format = RequestedFormat::new::<RgbAFormat>(RequestedFormatType::AbsoluteHighestFrameRate);
147 let mut camera = match open_camera(index) {
74 let mut camera = match Camera::new(index, format).and_then(|mut camera| camera.open_stream().map(|()| camera)) {
75 Ok(camera) => camera,
148 Ok(camera) => camera,
76 Err(error) => return failed(error.to_string()),
149 Err(error) => return failed(error.to_string()),
77 };
150 };
78 let mut blur_stage = BlurStage::new(blur);
151 let mut blur_stage = BlurStage::new(blur.clone());
152 let mut warned_undecodable = false;
79 while !stop.load(Ordering::SeqCst) {
153 while !stop.load(Ordering::SeqCst) {
80 let Ok(frame) = camera.frame() else {
154 let Ok(frame) = camera.frame() else {
81 std::thread::sleep(RETRY_PAUSE);
155 std::thread::sleep(RETRY_PAUSE);
82 continue;
156 continue;
83 };
157 };
84 let Ok(decoded) = frame.decode_image::<RgbAFormat>() else { continue };
158 let resolution = frame.resolution();
85 let (width, height) = (decoded.width(), decoded.height());
159 let (width, height) = (resolution.width(), resolution.height());
86 if width >= 2 && height >= 2 && width % 2 == 0 && height % 2 == 0 {
160 if width < 2 || height < 2 || width % 2 != 0 || height % 2 != 0 {
87 let mut rgba = decoded.into_raw();
161 continue;
88 blur_stage.apply_rgba(&mut rgba, width as usize, height as usize);
162 }
89 deliver(i420_from_rgba(&rgba, width, height));
163 if !blur.enabled()
164 && let Some(buffer) = direct_i420(frame.source_frame_format(), frame.buffer(), width, height)
165 {
166 deliver(buffer);
167 continue;
90 }
168 }
169 let Ok(decoded) = frame.decode_image::<RgbAFormat>() else {
170 if !std::mem::replace(&mut warned_undecodable, true) {
171 eprintln!("calls: camera delivers {} and no decoder is available", frame.source_frame_format());
172 }
173 continue;
174 };
175 let mut rgba = decoded.into_raw();
176 blur_stage.apply_rgba(&mut rgba, width as usize, height as usize);
177 deliver(i420_from_rgba(&rgba, width, height));
91 }
178 }
92 let _ = camera.stop_stream();
179 let _ = camera.stop_stream();
93 })
180 })
@@ -127,6 +214,26 @@ mod tests {
127 assert_eq!(entries[1].choice, DeviceChoice::Device("0".into()));
214 assert_eq!(entries[1].choice, DeviceChoice::Device("0".into()));
128 }
215 }
129
216
217 #[test]
218 fn yuyv_converts_to_i420_with_averaged_chroma() {
219 let row_a = [10u8, 100, 20, 200, 30, 50, 40, 60];
220 let row_b = [11u8, 120, 21, 220, 31, 70, 41, 80];
221 let data: Vec<u8> = row_a.iter().chain(row_b.iter()).copied().collect();
222 let mut buffer = i420_from_yuyv(&data, 4, 2).expect("converted");
223 let (plane_y, plane_u, plane_v) = buffer.data_mut();
224 assert_eq!(&plane_y[..4], &[10, 20, 30, 40]);
225 assert_eq!(plane_u[0], 110);
226 assert_eq!(plane_u[1], 60);
227 assert_eq!(plane_v[0], 210);
228 assert_eq!(plane_v[1], 70);
229 }
230
231 #[test]
232 fn short_raw_frames_are_rejected() {
233 assert!(i420_from_yuyv(&[0; 8], 4, 2).is_none());
234 assert!(i420_from_nv12(&[0; 8], 4, 2).is_none());
235 }
236
130 #[test]
237 #[test]
131 fn camera_choices_map_to_indices_or_names() {
238 fn camera_choices_map_to_indices_or_names() {
132 assert!(matches!(camera_index(&DeviceChoice::SystemDefault), CameraIndex::Index(0)));
239 assert!(matches!(camera_index(&DeviceChoice::SystemDefault), CameraIndex::Index(0)));
crates/calling/src/video_send.rs +6 −8
@@ -19,14 +19,13 @@ use crate::control::CallUpdate;
19 19 use crate::devices::DeviceChoice;
20 20 use crate::error::{Error, Result};
21 21 use crate::screen::{ShareSource, start_screen_capture};
22 use crate::video_frame::{FrameGate, SCREEN_FPS, VideoHub, VideoKey, picture_from_i420};
22 use crate::video_frame::{FrameGate, PERSON_FPS, SCREEN_FPS, VideoHub, VideoKey, picture_from_i420};
23 23 use crate::video_layout::VideoLines;
24 24 use crate::video_pattern::{PatternKind, spawn_pattern};
25 25
26 26 pub const VIDEO_MODE_ENV: &str = "CALLING_VIDEO";
27 27 const CAMERA_LABEL: &str = "camera";
28 28 const SCREEN_LABEL: &str = "screen";
29 const SELF_VIEW_FPS: u32 = 15;
30 29
31 30 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
32 31 pub enum VideoMode {
@@ -59,7 +58,7 @@ pub struct LocalSink {
59 58 impl LocalSink {
60 59 pub fn new(source: NativeVideoSource, hub: Option<(Arc<VideoHub>, VideoKey)>) -> Self {
61 60 let self_view = hub.map(|(hub, key)| {
62 let fps = if matches!(key, VideoKey::LocalScreen) { SCREEN_FPS } else { SELF_VIEW_FPS };
61 let fps = if matches!(key, VideoKey::LocalScreen) { SCREEN_FPS } else { PERSON_FPS };
63 62 (hub, key, FrameGate::new(fps))
64 63 });
65 64 LocalSink { source, self_view }
@@ -174,8 +173,8 @@ impl LocalVideo {
174 173 sender.set_parameters(parameters).map_err(|error| Error::Webrtc(error.to_string()))
175 174 }
176 175
177 fn sink(&self, outgoing: &Outgoing, key: VideoKey) -> LocalSink {
178 LocalSink::new(outgoing.source.clone(), Some((self.hub.clone(), key)))
176 fn camera_sink(&self) -> LocalSink {
177 LocalSink::new(self.camera.source.clone(), Some((self.hub.clone(), VideoKey::LocalCamera)))
179 178 }
180 179
181 180 fn report_failure(&self, what: &'static str) -> impl FnOnce(String) + Send + 'static {
@@ -191,7 +190,7 @@ impl LocalVideo {
191 190 return Err(Error::Webrtc("video is switched off".into()));
192 191 }
193 192 self.camera.capture = None;
194 let mut sink = self.sink(&self.camera, VideoKey::LocalCamera);
193 let mut sink = self.camera_sink();
195 194 let capture = match self.mode {
196 195 VideoMode::Pattern => Capture::Task(spawn_pattern(sink, PatternKind::Camera, Some(BlurStage::new(self.blur.clone())))),
197 196 _ => start_camera(choice, self.blur.clone(), move |buffer| sink.push(buffer), self.report_failure("Camera"))?,
@@ -216,7 +215,7 @@ impl LocalVideo {
216 215 return Err(Error::Webrtc("video is switched off".into()));
217 216 }
218 217 self.screen.capture = None;
219 let mut sink = self.sink(&self.screen, VideoKey::LocalScreen);
218 let mut sink = LocalSink::new(self.screen.source.clone(), None);
220 219 let capture = match self.mode {
221 220 VideoMode::Pattern => Capture::Task(spawn_pattern(sink, PatternKind::Screen, None)),
222 221 _ => start_screen_capture(source.clone(), move |buffer| sink.push(buffer), self.report_failure("Screen share"))?,
@@ -231,7 +230,6 @@ impl LocalVideo {
231 230 if let Some(share) = self.lines.as_ref().and_then(|lines| lines.share.as_ref()) {
232 231 let _ = Self::set_active(&share.sender(), false);
233 232 }
234 self.hub.forget(&VideoKey::LocalScreen);
235 233 }
236 234
237 235 pub fn stop_all(&mut self) {
@@ -19,14 +19,13 @@ use crate::control::CallUpdate;
19use crate::devices::DeviceChoice;
19use crate::devices::DeviceChoice;
20use crate::error::{Error, Result};
20use crate::error::{Error, Result};
21use crate::screen::{ShareSource, start_screen_capture};
21use crate::screen::{ShareSource, start_screen_capture};
22use crate::video_frame::{FrameGate, SCREEN_FPS, VideoHub, VideoKey, picture_from_i420};
22use crate::video_frame::{FrameGate, PERSON_FPS, SCREEN_FPS, VideoHub, VideoKey, picture_from_i420};
23use crate::video_layout::VideoLines;
23use crate::video_layout::VideoLines;
24use crate::video_pattern::{PatternKind, spawn_pattern};
24use crate::video_pattern::{PatternKind, spawn_pattern};
25
25
26pub const VIDEO_MODE_ENV: &str = "CALLING_VIDEO";
26pub const VIDEO_MODE_ENV: &str = "CALLING_VIDEO";
27const CAMERA_LABEL: &str = "camera";
27const CAMERA_LABEL: &str = "camera";
28const SCREEN_LABEL: &str = "screen";
28const SCREEN_LABEL: &str = "screen";
29const SELF_VIEW_FPS: u32 = 15;
30
29
31#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
30#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
32pub enum VideoMode {
31pub enum VideoMode {
@@ -59,7 +58,7 @@ pub struct LocalSink {
59impl LocalSink {
58impl LocalSink {
60 pub fn new(source: NativeVideoSource, hub: Option<(Arc<VideoHub>, VideoKey)>) -> Self {
59 pub fn new(source: NativeVideoSource, hub: Option<(Arc<VideoHub>, VideoKey)>) -> Self {
61 let self_view = hub.map(|(hub, key)| {
60 let self_view = hub.map(|(hub, key)| {
62 let fps = if matches!(key, VideoKey::LocalScreen) { SCREEN_FPS } else { SELF_VIEW_FPS };
61 let fps = if matches!(key, VideoKey::LocalScreen) { SCREEN_FPS } else { PERSON_FPS };
63 (hub, key, FrameGate::new(fps))
62 (hub, key, FrameGate::new(fps))
64 });
63 });
65 LocalSink { source, self_view }
64 LocalSink { source, self_view }
@@ -174,8 +173,8 @@ impl LocalVideo {
174 sender.set_parameters(parameters).map_err(|error| Error::Webrtc(error.to_string()))
173 sender.set_parameters(parameters).map_err(|error| Error::Webrtc(error.to_string()))
175 }
174 }
176
175
177 fn sink(&self, outgoing: &Outgoing, key: VideoKey) -> LocalSink {
176 fn camera_sink(&self) -> LocalSink {
178 LocalSink::new(outgoing.source.clone(), Some((self.hub.clone(), key)))
177 LocalSink::new(self.camera.source.clone(), Some((self.hub.clone(), VideoKey::LocalCamera)))
179 }
178 }
180
179
181 fn report_failure(&self, what: &'static str) -> impl FnOnce(String) + Send + 'static {
180 fn report_failure(&self, what: &'static str) -> impl FnOnce(String) + Send + 'static {
@@ -191,7 +190,7 @@ impl LocalVideo {
191 return Err(Error::Webrtc("video is switched off".into()));
190 return Err(Error::Webrtc("video is switched off".into()));
192 }
191 }
193 self.camera.capture = None;
192 self.camera.capture = None;
194 let mut sink = self.sink(&self.camera, VideoKey::LocalCamera);
193 let mut sink = self.camera_sink();
195 let capture = match self.mode {
194 let capture = match self.mode {
196 VideoMode::Pattern => Capture::Task(spawn_pattern(sink, PatternKind::Camera, Some(BlurStage::new(self.blur.clone())))),
195 VideoMode::Pattern => Capture::Task(spawn_pattern(sink, PatternKind::Camera, Some(BlurStage::new(self.blur.clone())))),
197 _ => start_camera(choice, self.blur.clone(), move |buffer| sink.push(buffer), self.report_failure("Camera"))?,
196 _ => start_camera(choice, self.blur.clone(), move |buffer| sink.push(buffer), self.report_failure("Camera"))?,
@@ -216,7 +215,7 @@ impl LocalVideo {
216 return Err(Error::Webrtc("video is switched off".into()));
215 return Err(Error::Webrtc("video is switched off".into()));
217 }
216 }
218 self.screen.capture = None;
217 self.screen.capture = None;
219 let mut sink = self.sink(&self.screen, VideoKey::LocalScreen);
218 let mut sink = LocalSink::new(self.screen.source.clone(), None);
220 let capture = match self.mode {
219 let capture = match self.mode {
221 VideoMode::Pattern => Capture::Task(spawn_pattern(sink, PatternKind::Screen, None)),
220 VideoMode::Pattern => Capture::Task(spawn_pattern(sink, PatternKind::Screen, None)),
222 _ => start_screen_capture(source.clone(), move |buffer| sink.push(buffer), self.report_failure("Screen share"))?,
221 _ => start_screen_capture(source.clone(), move |buffer| sink.push(buffer), self.report_failure("Screen share"))?,
@@ -231,7 +230,6 @@ impl LocalVideo {
231 if let Some(share) = self.lines.as_ref().and_then(|lines| lines.share.as_ref()) {
230 if let Some(share) = self.lines.as_ref().and_then(|lines| lines.share.as_ref()) {
232 let _ = Self::set_active(&share.sender(), false);
231 let _ = Self::set_active(&share.sender(), false);
233 }
232 }
234 self.hub.forget(&VideoKey::LocalScreen);
235 }
233 }
236
234
237 pub fn stop_all(&mut self) {
235 pub fn stop_all(&mut self) {