BlueGit

ict rusty-teams

feat(calls): computer sound when sharing, raise hand, reactions, meeting chat

| Before | After |
|---|---|
| Screen share without sound | "Include computer sound" in the share menu: system audio mixed into your audio like Teams; Windows excludes our own call playback (process loopback), Linux uses the sink monitor |
| - | Raise hand with queue order on the tile, raised hands sort first; organizer: lower a hand, lower all |
| - | Reactions (like, heart, applause, laugh, surprised), shown 3 s on the sender's tile |
| Chat only via the chat list | Chat button opens the meeting chat (or the call's chat) as a side panel next to the call |

- Verified live in a self-created Meet now meeting (only me): joined muted, meeting chat thread from the join answer read (HTTP 200), hand raised and lowered in the roster, 5/5 reactions echoed, share with computer sound while muted sent audio (level 0.30), meeting ended for everyone.
- Windows probe: process-exclude loopback available, 289 frames in 3 s.
- meet_now example gains --extras for this check.

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

metis Daniel Däschle · pushed by metis

Authored 2026-10-10 · 7 weeks ago

Hash
87fd274ce013f62de4bd5e0ba06a93ef4475f67c
Parent
cdded127
26 files changed +2099 −79
Cargo.lock +3 −0
@@ -992,6 +992,7 @@ version = "0.1.0"
992 992 dependencies = [
993 993 "base64 0.22.1",
994 994 "chatsvc",
995 "cpal",
995 996 "flate2",
996 997 "futures-util",
997 998 "libwebrtc",
@@ -1003,6 +1004,8 @@ dependencies = [
1003 1004 "tokio",
1004 1005 "uuid",
1005 1006 "webview",
1007 "windows 0.62.2",
1008 "windows-core 0.62.2",
1006 1009 ]
1007 1010
1008 1011 [[package]]
@@ -992,6 +992,7 @@ version = "0.1.0"
992dependencies = [
992dependencies = [
993 "base64 0.22.1",
993 "base64 0.22.1",
994 "chatsvc",
994 "chatsvc",
995 "cpal",
995 "flate2",
996 "flate2",
996 "futures-util",
997 "futures-util",
997 "libwebrtc",
998 "libwebrtc",
@@ -1003,6 +1004,8 @@ dependencies = [
1003 "tokio",
1004 "tokio",
1004 "uuid",
1005 "uuid",
1005 "webview",
1006 "webview",
1007 "windows 0.62.2",
1008 "windows-core 0.62.2",
1006]
1009]
1007
1010
1008[[package]]
1011[[package]]
ROADMAP.md +3 −2
@@ -2,7 +2,7 @@
2 2
3 3 Feature parity with the Microsoft Teams desktop client.
4 4
5 **Parity: 93 %** (79 done, 5 partial, 4 missing of 88). Partial counts half.
5 **Parity: 92 %** (79 done, 6 partial, 4 missing of 89). Partial counts half.
6 6
7 7 ## By area
8 8
@@ -18,7 +18,7 @@ Feature parity with the Microsoft Teams desktop client.
18 18 | [Search and navigation](#search-and-navigation) | 100 % | 5 | 0 | 0 |
19 19 | [Presence and people](#presence-and-people) | 100 % | 4 | 0 | 0 |
20 20 | [Look and settings](#look-and-settings) | 50 % | 2 | 0 | 2 |
21 | [Calls and meetings](#calls-and-meetings) | 67 % | 2 | 4 | 0 |
21 | [Calls and meetings](#calls-and-meetings) | 64 % | 2 | 5 | 0 |
22 22
23 23 ## Next
24 24
@@ -167,6 +167,7 @@ Feature parity with the Microsoft Teams desktop client.
167 167 | 1:1 and group calls | Partial | Phone button, Calling and Ringing tiles, end notices, direct to mixer renegotiation. Not yet tried with a second person |
168 168 | Join a meeting from a chat | Partial | Join button from the live meeting state, joins muted, roster tiles, lobby, Leave and End meeting. Audio only. Verified with a meeting of one; not yet with other participants |
169 169 | Video and screen sharing | Partial | Send and receive over libwebrtc H264, source requests through `applyChannelParameters`, stage, strip, self view, share banner. Sent frames acknowledged by the mixer; receive only checked by a local loopback, not with a second person. Incoming calls stay audio-only |
170 | Meeting extras | Partial | Share menu switch "Include computer sound" (remembered, mixed into the one audio track with the mic, own playback excluded on Windows 10 build 20348+), raise hand with queue badge, lower hand and Lower all hands for organizers, reactions on the sender's tile for 3 s, meeting chat in a 320 px side panel with unread badge. Checked with synthetic sources and the demo only; not yet live in a meeting or with a second person |
170 171 | In a call shown in presence | Done | "In a call", "In a meeting", "Presenting" from Teams activity on profile cards and chat headers; no notification sounds during a native call |
171 172
172 173 ## Agents
@@ -2,7 +2,7 @@
2
2
3Feature parity with the Microsoft Teams desktop client.
3Feature parity with the Microsoft Teams desktop client.
4
4
5**Parity: 93 %** (79 done, 5 partial, 4 missing of 88). Partial counts half.
5**Parity: 92 %** (79 done, 6 partial, 4 missing of 89). Partial counts half.
6
6
7## By area
7## By area
8
8
@@ -18,7 +18,7 @@ Feature parity with the Microsoft Teams desktop client.
18| [Search and navigation](#search-and-navigation) | 100 % | 5 | 0 | 0 |
18| [Search and navigation](#search-and-navigation) | 100 % | 5 | 0 | 0 |
19| [Presence and people](#presence-and-people) | 100 % | 4 | 0 | 0 |
19| [Presence and people](#presence-and-people) | 100 % | 4 | 0 | 0 |
20| [Look and settings](#look-and-settings) | 50 % | 2 | 0 | 2 |
20| [Look and settings](#look-and-settings) | 50 % | 2 | 0 | 2 |
21| [Calls and meetings](#calls-and-meetings) | 67 % | 2 | 4 | 0 |
21| [Calls and meetings](#calls-and-meetings) | 64 % | 2 | 5 | 0 |
22
22
23## Next
23## Next
24
24
@@ -167,6 +167,7 @@ Feature parity with the Microsoft Teams desktop client.
167| 1:1 and group calls | Partial | Phone button, Calling and Ringing tiles, end notices, direct to mixer renegotiation. Not yet tried with a second person |
167| 1:1 and group calls | Partial | Phone button, Calling and Ringing tiles, end notices, direct to mixer renegotiation. Not yet tried with a second person |
168| Join a meeting from a chat | Partial | Join button from the live meeting state, joins muted, roster tiles, lobby, Leave and End meeting. Audio only. Verified with a meeting of one; not yet with other participants |
168| Join a meeting from a chat | Partial | Join button from the live meeting state, joins muted, roster tiles, lobby, Leave and End meeting. Audio only. Verified with a meeting of one; not yet with other participants |
169| Video and screen sharing | Partial | Send and receive over libwebrtc H264, source requests through `applyChannelParameters`, stage, strip, self view, share banner. Sent frames acknowledged by the mixer; receive only checked by a local loopback, not with a second person. Incoming calls stay audio-only |
169| Video and screen sharing | Partial | Send and receive over libwebrtc H264, source requests through `applyChannelParameters`, stage, strip, self view, share banner. Sent frames acknowledged by the mixer; receive only checked by a local loopback, not with a second person. Incoming calls stay audio-only |
170| Meeting extras | Partial | Share menu switch "Include computer sound" (remembered, mixed into the one audio track with the mic, own playback excluded on Windows 10 build 20348+), raise hand with queue badge, lower hand and Lower all hands for organizers, reactions on the sender's tile for 3 s, meeting chat in a 320 px side panel with unread badge. Checked with synthetic sources and the demo only; not yet live in a meeting or with a second person |
170| In a call shown in presence | Done | "In a call", "In a meeting", "Presenting" from Teams activity on profile cards and chat headers; no notification sounds during a native call |
171| In a call shown in presence | Done | "In a call", "In a meeting", "Presenting" from Teams activity on profile cards and chat headers; no notification sounds during a native call |
171
172
172## Agents
173## Agents
crates/app/src/app_state.rs +3 −0
@@ -114,6 +114,7 @@ pub struct AppState {
114 114 pub call: Option<ActiveCall>,
115 115 pub call_launcher: Option<Arc<CallLauncher>>,
116 116 pub call_count: u64,
117 pub call_share_sound: bool,
117 118 pub rings: Rings,
118 119 pub live_meetings: HashMap<String, LiveMeeting>,
119 120 pub live_refreshing: HashSet<String>,
@@ -204,6 +205,7 @@ impl AppState {
204 205 call: None,
205 206 call_launcher: None,
206 207 call_count: 0,
208 call_share_sound: false,
207 209 rings: Rings::default(),
208 210 live_meetings: HashMap::new(),
209 211 live_refreshing: HashSet::new(),
@@ -211,6 +213,7 @@ impl AppState {
211 213 };
212 214 state.local_previews = load_local_previews(&state.store);
213 215 state.collapsed = state.load_collapsed();
216 state.call_share_sound = crate::call::load_share_sound(&state.store);
214 217 state.load_cached_translation_settings();
215 218 if !mode.demo {
216 219 state.directory.load_cached_presence(&state.store);
@@ -114,6 +114,7 @@ pub struct AppState {
114 pub call: Option<ActiveCall>,
114 pub call: Option<ActiveCall>,
115 pub call_launcher: Option<Arc<CallLauncher>>,
115 pub call_launcher: Option<Arc<CallLauncher>>,
116 pub call_count: u64,
116 pub call_count: u64,
117 pub call_share_sound: bool,
117 pub rings: Rings,
118 pub rings: Rings,
118 pub live_meetings: HashMap<String, LiveMeeting>,
119 pub live_meetings: HashMap<String, LiveMeeting>,
119 pub live_refreshing: HashSet<String>,
120 pub live_refreshing: HashSet<String>,
@@ -204,6 +205,7 @@ impl AppState {
204 call: None,
205 call: None,
205 call_launcher: None,
206 call_launcher: None,
206 call_count: 0,
207 call_count: 0,
208 call_share_sound: false,
207 rings: Rings::default(),
209 rings: Rings::default(),
208 live_meetings: HashMap::new(),
210 live_meetings: HashMap::new(),
209 live_refreshing: HashSet::new(),
211 live_refreshing: HashSet::new(),
@@ -211,6 +213,7 @@ impl AppState {
211 };
213 };
212 state.local_previews = load_local_previews(&state.store);
214 state.local_previews = load_local_previews(&state.store);
213 state.collapsed = state.load_collapsed();
215 state.collapsed = state.load_collapsed();
216 state.call_share_sound = crate::call::load_share_sound(&state.store);
214 state.load_cached_translation_settings();
217 state.load_cached_translation_settings();
215 if !mode.demo {
218 if !mode.demo {
216 state.directory.load_cached_presence(&state.store);
219 state.directory.load_cached_presence(&state.store);
crates/app/src/call/actions.rs +174 −6
@@ -2,7 +2,7 @@ use std::time::{Duration, Instant};
2 2
3 3 use calling::meeting::LiveMeeting;
4 4 use calling::{
5 CallCommand, CallHandle, CallSpec, CallUpdate, Callee, DeviceChoice, EngineEvent, MuteCommand, RingSignal, ShareSource, VideoKey,
5 CallCommand, CallHandle, CallSpec, CallUpdate, Callee, DeviceChoice, EngineEvent, MuteCommand, Reaction, RingSignal, ShareSource, VideoKey,
6 6 };
7 7 use gpui_kit::*;
8 8
@@ -27,6 +27,11 @@ const DEMO_CROWD: usize = 11;
27 27 const DEMO_SMALL_MEETING: usize = 4;
28 28 const DEMO_LIVE_MINUTES: i64 = 60;
29 29 const ORGID_PREFIX: &str = "8:orgid:";
30 pub const SHARE_SOUND_META_KEY: &str = "call_share_sound";
31
32 pub fn load_share_sound(store: &store::Store) -> bool {
33 store.meta(SHARE_SOUND_META_KEY).ok().flatten().as_deref() == Some("1")
34 }
30 35
31 36 fn now_unix() -> i64 {
32 37 chrono::Utc::now().timestamp()
@@ -147,7 +152,11 @@ impl AppState {
147 152 video,
148 153 pictures: CallPictures::default(),
149 154 stage_fullscreen: false,
155 chat_open: false,
150 156 });
157 if self.call_share_sound {
158 self.send_call_command(CallCommand::SetShareSound(true));
159 }
151 160 self.new_chat = false;
152 161 self.follow_call(call_id, updates, cx);
153 162 cx.emit(AppEvent::Call);
@@ -320,15 +329,64 @@ impl AppState {
320 329 cx.notify();
321 330 }
322 331
323 pub fn open_call_chat(&mut self, cx: &mut Context<Self>) {
324 let Some(conversation_id) = self.call.as_ref().and_then(|call| call.conversation_id.clone()) else {
332 pub fn toggle_call_chat(&mut self, cx: &mut Context<Self>) {
333 let Some(call) = self.call.as_mut().filter(|call| call.chat_thread().is_some()) else {
325 334 return;
326 335 };
327 if let Some(selection) = selection_for(&self.sidebar, &conversation_id) {
328 self.select(selection, cx);
336 call.chat_open = !call.chat_open;
337 cx.emit(AppEvent::Call);
338 cx.notify();
339 }
340
341 pub fn call_chat_thread(&self) -> Option<String> {
342 let call = self.call.as_ref().filter(|call| call.chat_open)?;
343 call.chat_thread().map(str::to_owned)
344 }
345
346 pub fn call_chat_unread(&self) -> u32 {
347 let Some(thread) = self.call.as_ref().filter(|call| !call.chat_open).and_then(|call| call.chat_thread()) else {
348 return 0;
349 };
350 let counted = self.directory.unread_counts.get(thread).copied();
351 counted.unwrap_or_else(|| u32::from(self.sidebar.chats.iter().any(|chat| chat.id == thread && chat.unread)))
352 }
353
354 pub fn toggle_call_hand(&mut self, _cx: &mut Context<Self>) {
355 let Some(call) = self.call.as_ref().filter(|call| call.model.is_active()) else {
356 return;
357 };
358 let raised = call.model.own_hand.is_none();
359 self.send_call_command(CallCommand::SetHand(raised));
360 }
361
362 pub fn lower_call_hand(&mut self, mri: String, _cx: &mut Context<Self>) {
363 let allowed = self.call.as_ref().is_some_and(|call| call.model.can_lower_hands());
364 if allowed {
365 self.send_call_command(CallCommand::LowerHand { mri });
329 366 }
330 367 }
331 368
369 pub fn lower_all_call_hands(&mut self, _cx: &mut Context<Self>) {
370 let allowed = self.call.as_ref().is_some_and(|call| call.model.can_lower_hands() && call.model.any_hand_raised());
371 if allowed {
372 self.send_call_command(CallCommand::LowerAllHands);
373 }
374 }
375
376 pub fn send_call_reaction(&mut self, reaction: Reaction, _cx: &mut Context<Self>) {
377 let live = self.call.as_ref().is_some_and(|call| call.model.is_active());
378 if live {
379 self.send_call_command(CallCommand::SendReaction(reaction));
380 }
381 }
382
383 pub fn set_call_share_sound(&mut self, on: bool, cx: &mut Context<Self>) {
384 self.call_share_sound = on;
385 let _ = self.store.set_meta(SHARE_SOUND_META_KEY, if on { "1" } else { "0" });
386 self.send_call_command(CallCommand::SetShareSound(on));
387 cx.notify();
388 }
389
332 390 pub fn toggle_stage_fullscreen(&mut self, cx: &mut Context<Self>) {
333 391 let Some(call) = self.call.as_mut().filter(|call| call.model.screen_sharer.is_some()) else {
334 392 return;
@@ -557,7 +615,7 @@ mod tests {
557 615 use std::sync::Arc;
558 616 use std::time::{Duration, Instant};
559 617
560 use calling::{CallState, CallUpdate, EndKind, EndReason, EngineEvent, call_channel};
618 use calling::{CallCommand, CallControl, CallState, CallUpdate, EndKind, EndReason, EngineEvent, Reaction, call_channel};
561 619 use gpui_kit::{AppContext as _, Entity, TestAppContext};
562 620 use store::{ChatRecord, MemberRecord, Store};
563 621
@@ -582,12 +640,122 @@ mod tests {
582 640 video: handle.video,
583 641 pictures: CallPictures::default(),
584 642 stage_fullscreen: false,
643 chat_open: false,
585 644 });
586 645 })
587 646 });
588 647 app
589 648 }
590 649
650 fn app_with_commands(cx: &mut TestAppContext, model: CallModel, conversation_id: Option<&str>) -> (Entity<AppState>, CallControl) {
651 cx.update(gpui_kit::init);
652 let store = Arc::new(Store::open_in_memory().unwrap());
653 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
654 let (handle, control) = call_channel();
655 let conversation_id = conversation_id.map(str::to_owned);
656 cx.update(|cx| {
657 app.update(cx, |state, _| {
658 state.call = Some(ActiveCall {
659 id: 7,
660 model,
661 commands: handle.commands,
662 viewing: true,
663 conversation_id,
664 video: handle.video,
665 pictures: CallPictures::default(),
666 stage_fullscreen: false,
667 chat_open: false,
668 });
669 })
670 });
671 (app, control)
672 }
673
674 fn live_meeting(can_end: bool) -> CallModel {
675 let mut model = CallModel::meeting("Standup", can_end);
676 model.apply(CallUpdate::State(CallState::Connected { since: Instant::now() }));
677 model.apply(CallUpdate::OwnIdentity { mri: "8:orgid:me".into() });
678 model
679 }
680
681 #[gpui_kit::test]
682 fn the_computer_sound_switch_is_remembered_and_sent_to_the_call(cx: &mut TestAppContext) {
683 let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
684 let store = cx.update(|cx| app.read(cx).store.clone());
685 assert!(!cx.update(|cx| app.read(cx).call_share_sound));
686 cx.update(|cx| app.update(cx, |state, cx| state.set_call_share_sound(true, cx)));
687 assert_eq!(control.try_recv_command(), Some(CallCommand::SetShareSound(true)));
688 let reopened = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
689 assert!(cx.update(|cx| reopened.read(cx).call_share_sound));
690 cx.update(|cx| app.update(cx, |state, cx| state.set_call_share_sound(false, cx)));
691 let reopened = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
692 assert!(!cx.update(|cx| reopened.read(cx).call_share_sound));
693 }
694
695 #[gpui_kit::test]
696 fn hands_and_reactions_become_call_commands_and_lowering_needs_the_organizer(cx: &mut TestAppContext) {
697 let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
698 cx.update(|cx| {
699 app.update(cx, |state, cx| {
700 state.toggle_call_hand(cx);
701 state.send_call_reaction(Reaction::Heart, cx);
702 state.lower_call_hand("8:orgid:a".into(), cx);
703 state.lower_all_call_hands(cx);
704 })
705 });
706 assert_eq!(control.try_recv_command(), Some(CallCommand::SetHand(true)));
707 assert_eq!(control.try_recv_command(), Some(CallCommand::SendReaction(Reaction::Heart)));
708 assert_eq!(control.try_recv_command(), None);
709 let (organizer, mut organizer_control) = app_with_commands(cx, live_meeting(true), None);
710 cx.update(|cx| {
711 organizer.update(cx, |state, cx| {
712 state.apply_call_update(7, CallUpdate::Roster(vec![calling::RosterEntry {
713 mri: "8:orgid:a".into(),
714 display_name: "Ana".into(),
715 muted: false,
716 in_lobby: false,
717 has_video: false,
718 sharing: false,
719 hand: Some(calling::RaisedHand { state_id: "s".into(), rank: 1 }),
720 }]), cx);
721 state.lower_call_hand("8:orgid:a".into(), cx);
722 state.lower_all_call_hands(cx);
723 })
724 });
725 assert_eq!(organizer_control.try_recv_command(), Some(CallCommand::LowerHand { mri: "8:orgid:a".into() }));
726 assert_eq!(organizer_control.try_recv_command(), Some(CallCommand::LowerAllHands));
727 }
728
729 #[gpui_kit::test]
730 fn the_chat_panel_opens_the_meeting_thread_and_the_badge_counts_only_while_closed(cx: &mut TestAppContext) {
731 let (app, _control) = app_with_commands(cx, live_meeting(false), Some("19:list@thread.v2"));
732 cx.update(|cx| {
733 app.update(cx, |state, cx| {
734 state.directory.unread_counts.insert("19:meeting_x@thread.v2".into(), 3);
735 assert_eq!(state.call_chat_thread(), None);
736 assert_eq!(state.call_chat_unread(), 0);
737 state.apply_call_update(7, CallUpdate::MeetingChat("19:meeting_x@thread.v2".into()), cx);
738 assert_eq!(state.call_chat_unread(), 3);
739 state.toggle_call_chat(cx);
740 assert_eq!(state.call_chat_thread().as_deref(), Some("19:meeting_x@thread.v2"));
741 assert_eq!(state.call_chat_unread(), 0);
742 state.toggle_call_chat(cx);
743 assert_eq!(state.call_chat_thread(), None);
744 })
745 });
746 }
747
748 #[gpui_kit::test]
749 fn a_call_without_a_chat_has_no_panel(cx: &mut TestAppContext) {
750 let app = app_with_call(cx);
751 cx.update(|cx| {
752 app.update(cx, |state, cx| {
753 state.toggle_call_chat(cx);
754 assert!(!state.call.as_ref().unwrap().chat_open);
755 })
756 });
757 }
758
591 759 fn app_with_chats(cx: &mut TestAppContext) -> Entity<AppState> {
592 760 cx.update(gpui_kit::init);
593 761 let store = Arc::new(Store::open_in_memory().unwrap());
@@ -2,7 +2,7 @@ use std::time::{Duration, Instant};
2
2
3use calling::meeting::LiveMeeting;
3use calling::meeting::LiveMeeting;
4use calling::{
4use calling::{
5 CallCommand, CallHandle, CallSpec, CallUpdate, Callee, DeviceChoice, EngineEvent, MuteCommand, RingSignal, ShareSource, VideoKey,
5 CallCommand, CallHandle, CallSpec, CallUpdate, Callee, DeviceChoice, EngineEvent, MuteCommand, Reaction, RingSignal, ShareSource, VideoKey,
6};
6};
7use gpui_kit::*;
7use gpui_kit::*;
8
8
@@ -27,6 +27,11 @@ const DEMO_CROWD: usize = 11;
27const DEMO_SMALL_MEETING: usize = 4;
27const DEMO_SMALL_MEETING: usize = 4;
28const DEMO_LIVE_MINUTES: i64 = 60;
28const DEMO_LIVE_MINUTES: i64 = 60;
29const ORGID_PREFIX: &str = "8:orgid:";
29const ORGID_PREFIX: &str = "8:orgid:";
30pub const SHARE_SOUND_META_KEY: &str = "call_share_sound";
31
32pub fn load_share_sound(store: &store::Store) -> bool {
33 store.meta(SHARE_SOUND_META_KEY).ok().flatten().as_deref() == Some("1")
34}
30
35
31fn now_unix() -> i64 {
36fn now_unix() -> i64 {
32 chrono::Utc::now().timestamp()
37 chrono::Utc::now().timestamp()
@@ -147,7 +152,11 @@ impl AppState {
147 video,
152 video,
148 pictures: CallPictures::default(),
153 pictures: CallPictures::default(),
149 stage_fullscreen: false,
154 stage_fullscreen: false,
155 chat_open: false,
150 });
156 });
157 if self.call_share_sound {
158 self.send_call_command(CallCommand::SetShareSound(true));
159 }
151 self.new_chat = false;
160 self.new_chat = false;
152 self.follow_call(call_id, updates, cx);
161 self.follow_call(call_id, updates, cx);
153 cx.emit(AppEvent::Call);
162 cx.emit(AppEvent::Call);
@@ -320,15 +329,64 @@ impl AppState {
320 cx.notify();
329 cx.notify();
321 }
330 }
322
331
323 pub fn open_call_chat(&mut self, cx: &mut Context<Self>) {
332 pub fn toggle_call_chat(&mut self, cx: &mut Context<Self>) {
324 let Some(conversation_id) = self.call.as_ref().and_then(|call| call.conversation_id.clone()) else {
333 let Some(call) = self.call.as_mut().filter(|call| call.chat_thread().is_some()) else {
325 return;
334 return;
326 };
335 };
327 if let Some(selection) = selection_for(&self.sidebar, &conversation_id) {
336 call.chat_open = !call.chat_open;
328 self.select(selection, cx);
337 cx.emit(AppEvent::Call);
338 cx.notify();
339 }
340
341 pub fn call_chat_thread(&self) -> Option<String> {
342 let call = self.call.as_ref().filter(|call| call.chat_open)?;
343 call.chat_thread().map(str::to_owned)
344 }
345
346 pub fn call_chat_unread(&self) -> u32 {
347 let Some(thread) = self.call.as_ref().filter(|call| !call.chat_open).and_then(|call| call.chat_thread()) else {
348 return 0;
349 };
350 let counted = self.directory.unread_counts.get(thread).copied();
351 counted.unwrap_or_else(|| u32::from(self.sidebar.chats.iter().any(|chat| chat.id == thread && chat.unread)))
352 }
353
354 pub fn toggle_call_hand(&mut self, _cx: &mut Context<Self>) {
355 let Some(call) = self.call.as_ref().filter(|call| call.model.is_active()) else {
356 return;
357 };
358 let raised = call.model.own_hand.is_none();
359 self.send_call_command(CallCommand::SetHand(raised));
360 }
361
362 pub fn lower_call_hand(&mut self, mri: String, _cx: &mut Context<Self>) {
363 let allowed = self.call.as_ref().is_some_and(|call| call.model.can_lower_hands());
364 if allowed {
365 self.send_call_command(CallCommand::LowerHand { mri });
329 }
366 }
330 }
367 }
331
368
369 pub fn lower_all_call_hands(&mut self, _cx: &mut Context<Self>) {
370 let allowed = self.call.as_ref().is_some_and(|call| call.model.can_lower_hands() && call.model.any_hand_raised());
371 if allowed {
372 self.send_call_command(CallCommand::LowerAllHands);
373 }
374 }
375
376 pub fn send_call_reaction(&mut self, reaction: Reaction, _cx: &mut Context<Self>) {
377 let live = self.call.as_ref().is_some_and(|call| call.model.is_active());
378 if live {
379 self.send_call_command(CallCommand::SendReaction(reaction));
380 }
381 }
382
383 pub fn set_call_share_sound(&mut self, on: bool, cx: &mut Context<Self>) {
384 self.call_share_sound = on;
385 let _ = self.store.set_meta(SHARE_SOUND_META_KEY, if on { "1" } else { "0" });
386 self.send_call_command(CallCommand::SetShareSound(on));
387 cx.notify();
388 }
389
332 pub fn toggle_stage_fullscreen(&mut self, cx: &mut Context<Self>) {
390 pub fn toggle_stage_fullscreen(&mut self, cx: &mut Context<Self>) {
333 let Some(call) = self.call.as_mut().filter(|call| call.model.screen_sharer.is_some()) else {
391 let Some(call) = self.call.as_mut().filter(|call| call.model.screen_sharer.is_some()) else {
334 return;
392 return;
@@ -557,7 +615,7 @@ mod tests {
557 use std::sync::Arc;
615 use std::sync::Arc;
558 use std::time::{Duration, Instant};
616 use std::time::{Duration, Instant};
559
617
560 use calling::{CallState, CallUpdate, EndKind, EndReason, EngineEvent, call_channel};
618 use calling::{CallCommand, CallControl, CallState, CallUpdate, EndKind, EndReason, EngineEvent, Reaction, call_channel};
561 use gpui_kit::{AppContext as _, Entity, TestAppContext};
619 use gpui_kit::{AppContext as _, Entity, TestAppContext};
562 use store::{ChatRecord, MemberRecord, Store};
620 use store::{ChatRecord, MemberRecord, Store};
563
621
@@ -582,12 +640,122 @@ mod tests {
582 video: handle.video,
640 video: handle.video,
583 pictures: CallPictures::default(),
641 pictures: CallPictures::default(),
584 stage_fullscreen: false,
642 stage_fullscreen: false,
643 chat_open: false,
585 });
644 });
586 })
645 })
587 });
646 });
588 app
647 app
589 }
648 }
590
649
650 fn app_with_commands(cx: &mut TestAppContext, model: CallModel, conversation_id: Option<&str>) -> (Entity<AppState>, CallControl) {
651 cx.update(gpui_kit::init);
652 let store = Arc::new(Store::open_in_memory().unwrap());
653 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
654 let (handle, control) = call_channel();
655 let conversation_id = conversation_id.map(str::to_owned);
656 cx.update(|cx| {
657 app.update(cx, |state, _| {
658 state.call = Some(ActiveCall {
659 id: 7,
660 model,
661 commands: handle.commands,
662 viewing: true,
663 conversation_id,
664 video: handle.video,
665 pictures: CallPictures::default(),
666 stage_fullscreen: false,
667 chat_open: false,
668 });
669 })
670 });
671 (app, control)
672 }
673
674 fn live_meeting(can_end: bool) -> CallModel {
675 let mut model = CallModel::meeting("Standup", can_end);
676 model.apply(CallUpdate::State(CallState::Connected { since: Instant::now() }));
677 model.apply(CallUpdate::OwnIdentity { mri: "8:orgid:me".into() });
678 model
679 }
680
681 #[gpui_kit::test]
682 fn the_computer_sound_switch_is_remembered_and_sent_to_the_call(cx: &mut TestAppContext) {
683 let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
684 let store = cx.update(|cx| app.read(cx).store.clone());
685 assert!(!cx.update(|cx| app.read(cx).call_share_sound));
686 cx.update(|cx| app.update(cx, |state, cx| state.set_call_share_sound(true, cx)));
687 assert_eq!(control.try_recv_command(), Some(CallCommand::SetShareSound(true)));
688 let reopened = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
689 assert!(cx.update(|cx| reopened.read(cx).call_share_sound));
690 cx.update(|cx| app.update(cx, |state, cx| state.set_call_share_sound(false, cx)));
691 let reopened = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
692 assert!(!cx.update(|cx| reopened.read(cx).call_share_sound));
693 }
694
695 #[gpui_kit::test]
696 fn hands_and_reactions_become_call_commands_and_lowering_needs_the_organizer(cx: &mut TestAppContext) {
697 let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
698 cx.update(|cx| {
699 app.update(cx, |state, cx| {
700 state.toggle_call_hand(cx);
701 state.send_call_reaction(Reaction::Heart, cx);
702 state.lower_call_hand("8:orgid:a".into(), cx);
703 state.lower_all_call_hands(cx);
704 })
705 });
706 assert_eq!(control.try_recv_command(), Some(CallCommand::SetHand(true)));
707 assert_eq!(control.try_recv_command(), Some(CallCommand::SendReaction(Reaction::Heart)));
708 assert_eq!(control.try_recv_command(), None);
709 let (organizer, mut organizer_control) = app_with_commands(cx, live_meeting(true), None);
710 cx.update(|cx| {
711 organizer.update(cx, |state, cx| {
712 state.apply_call_update(7, CallUpdate::Roster(vec![calling::RosterEntry {
713 mri: "8:orgid:a".into(),
714 display_name: "Ana".into(),
715 muted: false,
716 in_lobby: false,
717 has_video: false,
718 sharing: false,
719 hand: Some(calling::RaisedHand { state_id: "s".into(), rank: 1 }),
720 }]), cx);
721 state.lower_call_hand("8:orgid:a".into(), cx);
722 state.lower_all_call_hands(cx);
723 })
724 });
725 assert_eq!(organizer_control.try_recv_command(), Some(CallCommand::LowerHand { mri: "8:orgid:a".into() }));
726 assert_eq!(organizer_control.try_recv_command(), Some(CallCommand::LowerAllHands));
727 }
728
729 #[gpui_kit::test]
730 fn the_chat_panel_opens_the_meeting_thread_and_the_badge_counts_only_while_closed(cx: &mut TestAppContext) {
731 let (app, _control) = app_with_commands(cx, live_meeting(false), Some("19:list@thread.v2"));
732 cx.update(|cx| {
733 app.update(cx, |state, cx| {
734 state.directory.unread_counts.insert("19:meeting_x@thread.v2".into(), 3);
735 assert_eq!(state.call_chat_thread(), None);
736 assert_eq!(state.call_chat_unread(), 0);
737 state.apply_call_update(7, CallUpdate::MeetingChat("19:meeting_x@thread.v2".into()), cx);
738 assert_eq!(state.call_chat_unread(), 3);
739 state.toggle_call_chat(cx);
740 assert_eq!(state.call_chat_thread().as_deref(), Some("19:meeting_x@thread.v2"));
741 assert_eq!(state.call_chat_unread(), 0);
742 state.toggle_call_chat(cx);
743 assert_eq!(state.call_chat_thread(), None);
744 })
745 });
746 }
747
748 #[gpui_kit::test]
749 fn a_call_without_a_chat_has_no_panel(cx: &mut TestAppContext) {
750 let app = app_with_call(cx);
751 cx.update(|cx| {
752 app.update(cx, |state, cx| {
753 state.toggle_call_chat(cx);
754 assert!(!state.call.as_ref().unwrap().chat_open);
755 })
756 });
757 }
758
591 fn app_with_chats(cx: &mut TestAppContext) -> Entity<AppState> {
759 fn app_with_chats(cx: &mut TestAppContext) -> Entity<AppState> {
592 cx.update(gpui_kit::init);
760 cx.update(gpui_kit::init);
593 let store = Arc::new(Store::open_in_memory().unwrap());
761 let store = Arc::new(Store::open_in_memory().unwrap());
crates/app/src/call/demo.rs +82 −5
@@ -4,7 +4,7 @@ use calling::video_frame::bgra_from_i420;
4 4 use calling::video_pattern::{PatternKind, pattern_frame};
5 5 use calling::{
6 6 AudioDevice, CallCommand, CallControl, CallHandle, CallState, CallUpdate, Caller, DeviceChoice, DeviceLists, EndReason,
7 IncomingRing, Progress, RosterEntry, ShareKind, ShareSource, VideoKey, call_channel,
7 IncomingRing, Progress, RaisedHand, Reaction, RosterEntry, ShareKind, ShareSource, VideoKey, call_channel,
8 8 };
9 9 use calling::CameraDevice;
10 10 use tokio::time::{interval, sleep};
@@ -27,6 +27,8 @@ const DEMO_CAMERAS: usize = 4;
27 27 const SCREEN_EVERY_TICKS: u32 = 4;
28 28 const SHARE_START: Duration = Duration::from_secs(10);
29 29 const SHARE_END: Duration = Duration::from_secs(45);
30 const REACTION_EVERY_TICKS: u32 = 20;
31 const DEMO_FIRST_HANDS: [(usize, u64); 2] = [(2, 1), (0, 2)];
30 32 const GUEST_PHASE: u32 = 37;
31 33 const SELF_PHASE: u32 = 211;
32 34 pub const DEMO_OWN_MRI: &str = "8:orgid:demo-me";
@@ -129,6 +131,7 @@ fn roster_of(people: &[Person]) -> Vec<RosterEntry> {
129 131 in_lobby: false,
130 132 has_video: index < DEMO_CAMERAS,
131 133 sharing: false,
134 hand: None,
132 135 })
133 136 .collect()
134 137 }
@@ -168,10 +171,18 @@ async fn run_demo_call(mut control: CallControl, script: DemoCall) {
168 171 }
169 172 control.send(CallUpdate::Lobby(false));
170 173 }
171 control.send(CallUpdate::Roster(roster_of(&people)));
174 let mut roster = roster_of(&people);
175 if matches!(script, DemoCall::Meeting { .. }) {
176 for (index, rank) in DEMO_FIRST_HANDS {
177 if let Some(entry) = roster.get_mut(index) {
178 entry.hand = Some(demo_hand(rank));
179 }
180 }
181 }
182 control.send(CallUpdate::Roster(roster.clone()));
172 183 let video = !matches!(script, DemoCall::Test);
173 184 let sharer = matches!(script, DemoCall::Meeting { .. }).then(|| people.get(1).map(|person| person.0.clone())).flatten();
174 speak_until_hangup(control, people, video, sharer).await;
185 speak_until_hangup(control, people, roster, video, sharer).await;
175 186 }
176 187
177 188 async fn ring_until_answered(control: &mut CallControl, script: &DemoCall) -> bool {
@@ -207,7 +218,7 @@ fn publish_demo_video(control: &CallControl, people: &[Person], tick: u32, shari
207 218 }
208 219 }
209 220
210 async fn speak_until_hangup(mut control: CallControl, people: Vec<Person>, video: bool, sharer: Option<String>) {
221 async fn speak_until_hangup(mut control: CallControl, people: Vec<Person>, mut roster: Vec<RosterEntry>, video: bool, sharer: Option<String>) {
211 222 let started = Instant::now();
212 223 let mut video_ticks = 0u32;
213 224 let mut sharing = false;
@@ -217,6 +228,7 @@ async fn speak_until_hangup(mut control: CallControl, people: Vec<Person>, video
217 228 let mut input = DeviceChoice::SystemDefault;
218 229 let mut output = DeviceChoice::SystemDefault;
219 230 let mut ticks = 0u32;
231 let mut share_sound = false;
220 232 let mut tick = interval(LEVEL_PERIOD);
221 233 loop {
222 234 tokio::select! {
@@ -241,6 +253,12 @@ async fn speak_until_hangup(mut control: CallControl, people: Vec<Person>, video
241 253 let speaker = &people[(ticks / SPEAKER_TICKS) as usize % people.len()];
242 254 control.send(CallUpdate::Speakers(vec![speaker.0.clone()]));
243 255 }
256 if ticks % REACTION_EVERY_TICKS == REACTION_EVERY_TICKS / 2
257 && let Some((mri, _)) = people.get((ticks / REACTION_EVERY_TICKS) as usize % people.len().max(1))
258 {
259 let reaction = Reaction::ALL[(ticks / REACTION_EVERY_TICKS) as usize % Reaction::ALL.len()];
260 control.send(CallUpdate::Reaction { mri: mri.clone(), reaction });
261 }
244 262 ticks += 1;
245 263 }
246 264 command = control.recv() => match command {
@@ -262,8 +280,29 @@ async fn speak_until_hangup(mut control: CallControl, people: Vec<Person>, video
262 280 control.send(CallUpdate::Camera(on));
263 281 }
264 282 Some(CallCommand::SelectCamera(_)) => {}
265 Some(CallCommand::StartShare(source)) => control.send(CallUpdate::LocalShare(Some(source.label()))),
283 Some(CallCommand::StartShare(source)) => {
284 control.send(CallUpdate::LocalShare(Some(source.label())));
285 if share_sound {
286 control.send(CallUpdate::ShareSound(true));
287 }
288 }
266 289 Some(CallCommand::StopShare) => control.send(CallUpdate::LocalShare(None)),
290 Some(CallCommand::SetShareSound(on)) => share_sound = on,
291 Some(CallCommand::SetHand(raised)) => {
292 set_demo_hand(&mut roster, DEMO_OWN_MRI, raised);
293 control.send(CallUpdate::Roster(roster.clone()));
294 }
295 Some(CallCommand::LowerHand { mri }) => {
296 set_demo_hand(&mut roster, &mri, false);
297 control.send(CallUpdate::Roster(roster.clone()));
298 }
299 Some(CallCommand::LowerAllHands) => {
300 roster.iter_mut().for_each(|entry| entry.hand = None);
301 control.send(CallUpdate::Roster(roster.clone()));
302 }
303 Some(CallCommand::SendReaction(reaction)) => {
304 control.send(CallUpdate::Reaction { mri: DEMO_OWN_MRI.to_owned(), reaction });
305 }
267 306 Some(CallCommand::RefreshShareSources) => control.send(CallUpdate::ShareSources(demo_share_sources())),
268 307 Some(CallCommand::Hangup | CallCommand::EndMeeting) | None => {
269 308 end(&control, EndReason::LocalHangup);
@@ -274,6 +313,33 @@ async fn speak_until_hangup(mut control: CallControl, people: Vec<Person>, video
274 313 }
275 314 }
276 315
316 fn demo_hand(rank: u64) -> RaisedHand {
317 RaisedHand { state_id: format!("demo-hand-{rank}"), rank }
318 }
319
320 fn set_demo_hand(roster: &mut Vec<RosterEntry>, mri: &str, raised: bool) {
321 let next_rank = roster.iter().filter_map(|entry| entry.hand.as_ref().map(|hand| hand.rank)).max().unwrap_or(0) + 1;
322 if !raised {
323 if let Some(entry) = roster.iter_mut().find(|entry| entry.mri == mri) {
324 entry.hand = None;
325 }
326 roster.retain(|entry| entry.mri != DEMO_OWN_MRI || entry.hand.is_some());
327 return;
328 }
329 match roster.iter_mut().find(|entry| entry.mri == mri) {
330 Some(entry) => entry.hand = Some(demo_hand(next_rank)),
331 None => roster.push(RosterEntry {
332 mri: mri.to_owned(),
333 display_name: "You".to_owned(),
334 muted: false,
335 in_lobby: false,
336 has_video: false,
337 sharing: false,
338 hand: Some(demo_hand(next_rank)),
339 }),
340 }
341 }
342
277 343 fn end(control: &CallControl, reason: EndReason) {
278 344 control.send(CallUpdate::State(CallState::Ended { reason }));
279 345 }
@@ -292,6 +358,17 @@ mod tests {
292 358 assert_eq!(mris.len(), 11);
293 359 }
294 360
361 #[test]
362 fn demo_hands_queue_in_order_and_lowering_drops_the_own_entry() {
363 let mut roster = roster_of(&demo_guests(3));
364 set_demo_hand(&mut roster, "8:orgid:demo-guest-1", true);
365 set_demo_hand(&mut roster, DEMO_OWN_MRI, true);
366 let ranks: Vec<u64> = roster.iter().filter_map(|entry| entry.hand.as_ref().map(|hand| hand.rank)).collect();
367 assert_eq!(ranks, vec![1, 2]);
368 set_demo_hand(&mut roster, DEMO_OWN_MRI, false);
369 assert!(roster.iter().all(|entry| entry.mri != DEMO_OWN_MRI));
370 }
371
295 372 #[test]
296 373 fn the_demo_ring_names_a_caller_and_a_chat() {
297 374 let ring = demo_ring();
@@ -4,7 +4,7 @@ use calling::video_frame::bgra_from_i420;
4use calling::video_pattern::{PatternKind, pattern_frame};
4use calling::video_pattern::{PatternKind, pattern_frame};
5use calling::{
5use calling::{
6 AudioDevice, CallCommand, CallControl, CallHandle, CallState, CallUpdate, Caller, DeviceChoice, DeviceLists, EndReason,
6 AudioDevice, CallCommand, CallControl, CallHandle, CallState, CallUpdate, Caller, DeviceChoice, DeviceLists, EndReason,
7 IncomingRing, Progress, RosterEntry, ShareKind, ShareSource, VideoKey, call_channel,
7 IncomingRing, Progress, RaisedHand, Reaction, RosterEntry, ShareKind, ShareSource, VideoKey, call_channel,
8};
8};
9use calling::CameraDevice;
9use calling::CameraDevice;
10use tokio::time::{interval, sleep};
10use tokio::time::{interval, sleep};
@@ -27,6 +27,8 @@ const DEMO_CAMERAS: usize = 4;
27const SCREEN_EVERY_TICKS: u32 = 4;
27const SCREEN_EVERY_TICKS: u32 = 4;
28const SHARE_START: Duration = Duration::from_secs(10);
28const SHARE_START: Duration = Duration::from_secs(10);
29const SHARE_END: Duration = Duration::from_secs(45);
29const SHARE_END: Duration = Duration::from_secs(45);
30const REACTION_EVERY_TICKS: u32 = 20;
31const DEMO_FIRST_HANDS: [(usize, u64); 2] = [(2, 1), (0, 2)];
30const GUEST_PHASE: u32 = 37;
32const GUEST_PHASE: u32 = 37;
31const SELF_PHASE: u32 = 211;
33const SELF_PHASE: u32 = 211;
32pub const DEMO_OWN_MRI: &str = "8:orgid:demo-me";
34pub const DEMO_OWN_MRI: &str = "8:orgid:demo-me";
@@ -129,6 +131,7 @@ fn roster_of(people: &[Person]) -> Vec<RosterEntry> {
129 in_lobby: false,
131 in_lobby: false,
130 has_video: index < DEMO_CAMERAS,
132 has_video: index < DEMO_CAMERAS,
131 sharing: false,
133 sharing: false,
134 hand: None,
132 })
135 })
133 .collect()
136 .collect()
134}
137}
@@ -168,10 +171,18 @@ async fn run_demo_call(mut control: CallControl, script: DemoCall) {
168 }
171 }
169 control.send(CallUpdate::Lobby(false));
172 control.send(CallUpdate::Lobby(false));
170 }
173 }
171 control.send(CallUpdate::Roster(roster_of(&people)));
174 let mut roster = roster_of(&people);
175 if matches!(script, DemoCall::Meeting { .. }) {
176 for (index, rank) in DEMO_FIRST_HANDS {
177 if let Some(entry) = roster.get_mut(index) {
178 entry.hand = Some(demo_hand(rank));
179 }
180 }
181 }
182 control.send(CallUpdate::Roster(roster.clone()));
172 let video = !matches!(script, DemoCall::Test);
183 let video = !matches!(script, DemoCall::Test);
173 let sharer = matches!(script, DemoCall::Meeting { .. }).then(|| people.get(1).map(|person| person.0.clone())).flatten();
184 let sharer = matches!(script, DemoCall::Meeting { .. }).then(|| people.get(1).map(|person| person.0.clone())).flatten();
174 speak_until_hangup(control, people, video, sharer).await;
185 speak_until_hangup(control, people, roster, video, sharer).await;
175}
186}
176
187
177async fn ring_until_answered(control: &mut CallControl, script: &DemoCall) -> bool {
188async fn ring_until_answered(control: &mut CallControl, script: &DemoCall) -> bool {
@@ -207,7 +218,7 @@ fn publish_demo_video(control: &CallControl, people: &[Person], tick: u32, shari
207 }
218 }
208}
219}
209
220
210async fn speak_until_hangup(mut control: CallControl, people: Vec<Person>, video: bool, sharer: Option<String>) {
221async fn speak_until_hangup(mut control: CallControl, people: Vec<Person>, mut roster: Vec<RosterEntry>, video: bool, sharer: Option<String>) {
211 let started = Instant::now();
222 let started = Instant::now();
212 let mut video_ticks = 0u32;
223 let mut video_ticks = 0u32;
213 let mut sharing = false;
224 let mut sharing = false;
@@ -217,6 +228,7 @@ async fn speak_until_hangup(mut control: CallControl, people: Vec<Person>, video
217 let mut input = DeviceChoice::SystemDefault;
228 let mut input = DeviceChoice::SystemDefault;
218 let mut output = DeviceChoice::SystemDefault;
229 let mut output = DeviceChoice::SystemDefault;
219 let mut ticks = 0u32;
230 let mut ticks = 0u32;
231 let mut share_sound = false;
220 let mut tick = interval(LEVEL_PERIOD);
232 let mut tick = interval(LEVEL_PERIOD);
221 loop {
233 loop {
222 tokio::select! {
234 tokio::select! {
@@ -241,6 +253,12 @@ async fn speak_until_hangup(mut control: CallControl, people: Vec<Person>, video
241 let speaker = &people[(ticks / SPEAKER_TICKS) as usize % people.len()];
253 let speaker = &people[(ticks / SPEAKER_TICKS) as usize % people.len()];
242 control.send(CallUpdate::Speakers(vec![speaker.0.clone()]));
254 control.send(CallUpdate::Speakers(vec![speaker.0.clone()]));
243 }
255 }
256 if ticks % REACTION_EVERY_TICKS == REACTION_EVERY_TICKS / 2
257 && let Some((mri, _)) = people.get((ticks / REACTION_EVERY_TICKS) as usize % people.len().max(1))
258 {
259 let reaction = Reaction::ALL[(ticks / REACTION_EVERY_TICKS) as usize % Reaction::ALL.len()];
260 control.send(CallUpdate::Reaction { mri: mri.clone(), reaction });
261 }
244 ticks += 1;
262 ticks += 1;
245 }
263 }
246 command = control.recv() => match command {
264 command = control.recv() => match command {
@@ -262,8 +280,29 @@ async fn speak_until_hangup(mut control: CallControl, people: Vec<Person>, video
262 control.send(CallUpdate::Camera(on));
280 control.send(CallUpdate::Camera(on));
263 }
281 }
264 Some(CallCommand::SelectCamera(_)) => {}
282 Some(CallCommand::SelectCamera(_)) => {}
265 Some(CallCommand::StartShare(source)) => control.send(CallUpdate::LocalShare(Some(source.label()))),
283 Some(CallCommand::StartShare(source)) => {
284 control.send(CallUpdate::LocalShare(Some(source.label())));
285 if share_sound {
286 control.send(CallUpdate::ShareSound(true));
287 }
288 }
266 Some(CallCommand::StopShare) => control.send(CallUpdate::LocalShare(None)),
289 Some(CallCommand::StopShare) => control.send(CallUpdate::LocalShare(None)),
290 Some(CallCommand::SetShareSound(on)) => share_sound = on,
291 Some(CallCommand::SetHand(raised)) => {
292 set_demo_hand(&mut roster, DEMO_OWN_MRI, raised);
293 control.send(CallUpdate::Roster(roster.clone()));
294 }
295 Some(CallCommand::LowerHand { mri }) => {
296 set_demo_hand(&mut roster, &mri, false);
297 control.send(CallUpdate::Roster(roster.clone()));
298 }
299 Some(CallCommand::LowerAllHands) => {
300 roster.iter_mut().for_each(|entry| entry.hand = None);
301 control.send(CallUpdate::Roster(roster.clone()));
302 }
303 Some(CallCommand::SendReaction(reaction)) => {
304 control.send(CallUpdate::Reaction { mri: DEMO_OWN_MRI.to_owned(), reaction });
305 }
267 Some(CallCommand::RefreshShareSources) => control.send(CallUpdate::ShareSources(demo_share_sources())),
306 Some(CallCommand::RefreshShareSources) => control.send(CallUpdate::ShareSources(demo_share_sources())),
268 Some(CallCommand::Hangup | CallCommand::EndMeeting) | None => {
307 Some(CallCommand::Hangup | CallCommand::EndMeeting) | None => {
269 end(&control, EndReason::LocalHangup);
308 end(&control, EndReason::LocalHangup);
@@ -274,6 +313,33 @@ async fn speak_until_hangup(mut control: CallControl, people: Vec<Person>, video
274 }
313 }
275}
314}
276
315
316fn demo_hand(rank: u64) -> RaisedHand {
317 RaisedHand { state_id: format!("demo-hand-{rank}"), rank }
318}
319
320fn set_demo_hand(roster: &mut Vec<RosterEntry>, mri: &str, raised: bool) {
321 let next_rank = roster.iter().filter_map(|entry| entry.hand.as_ref().map(|hand| hand.rank)).max().unwrap_or(0) + 1;
322 if !raised {
323 if let Some(entry) = roster.iter_mut().find(|entry| entry.mri == mri) {
324 entry.hand = None;
325 }
326 roster.retain(|entry| entry.mri != DEMO_OWN_MRI || entry.hand.is_some());
327 return;
328 }
329 match roster.iter_mut().find(|entry| entry.mri == mri) {
330 Some(entry) => entry.hand = Some(demo_hand(next_rank)),
331 None => roster.push(RosterEntry {
332 mri: mri.to_owned(),
333 display_name: "You".to_owned(),
334 muted: false,
335 in_lobby: false,
336 has_video: false,
337 sharing: false,
338 hand: Some(demo_hand(next_rank)),
339 }),
340 }
341}
342
277fn end(control: &CallControl, reason: EndReason) {
343fn end(control: &CallControl, reason: EndReason) {
278 control.send(CallUpdate::State(CallState::Ended { reason }));
344 control.send(CallUpdate::State(CallState::Ended { reason }));
279}
345}
@@ -292,6 +358,17 @@ mod tests {
292 assert_eq!(mris.len(), 11);
358 assert_eq!(mris.len(), 11);
293 }
359 }
294
360
361 #[test]
362 fn demo_hands_queue_in_order_and_lowering_drops_the_own_entry() {
363 let mut roster = roster_of(&demo_guests(3));
364 set_demo_hand(&mut roster, "8:orgid:demo-guest-1", true);
365 set_demo_hand(&mut roster, DEMO_OWN_MRI, true);
366 let ranks: Vec<u64> = roster.iter().filter_map(|entry| entry.hand.as_ref().map(|hand| hand.rank)).collect();
367 assert_eq!(ranks, vec![1, 2]);
368 set_demo_hand(&mut roster, DEMO_OWN_MRI, false);
369 assert!(roster.iter().all(|entry| entry.mri != DEMO_OWN_MRI));
370 }
371
295 #[test]
372 #[test]
296 fn the_demo_ring_names_a_caller_and_a_chat() {
373 fn the_demo_ring_names_a_caller_and_a_chat() {
297 let ring = demo_ring();
374 let ring = demo_ring();
crates/app/src/call/mod.rs +2 −1
@@ -6,7 +6,8 @@ mod pictures;
6 6 mod ring;
7 7 mod target;
8 8
9 pub use actions::load_share_sound;
9 10 pub use launcher::CallLauncher;
10 pub use model::{ActiveCall, CallKind, CallModel, GridLayout, Tile, TileSize, TileState, grid_layout, tile_size};
11 pub use model::{ActiveCall, CHAT_OPEN_TILES, CallKind, CallModel, GridLayout, MAX_TILES, REACTION_SHOWN, Tile, TileSize, TileState, grid_layout, tile_size};
11 12 pub use ring::{MissedCall, RingEntry, Rings};
12 13 pub use target::plan_for_chat;
@@ -6,7 +6,8 @@ mod pictures;
6mod ring;
6mod ring;
7mod target;
7mod target;
8
8
9pub use actions::load_share_sound;
9pub use launcher::CallLauncher;
10pub use launcher::CallLauncher;
10pub use model::{ActiveCall, CallKind, CallModel, GridLayout, Tile, TileSize, TileState, grid_layout, tile_size};
11pub use model::{ActiveCall, CHAT_OPEN_TILES, CallKind, CallModel, GridLayout, MAX_TILES, REACTION_SHOWN, Tile, TileSize, TileState, grid_layout, tile_size};
11pub use ring::{MissedCall, RingEntry, Rings};
12pub use ring::{MissedCall, RingEntry, Rings};
12pub use target::plan_for_chat;
13pub use target::plan_for_chat;
crates/app/src/call/model.rs +191 −14
@@ -2,7 +2,7 @@ use std::sync::Arc;
2 2 use std::time::{Duration, Instant};
3 3
4 4 use calling::{
5 CallCommand, CallState, CallUpdate, CameraDevice, DeviceChoice, DeviceLists, EndKind, EndReason, Progress, RosterEntry,
5 CallCommand, CallState, CallUpdate, CameraDevice, DeviceChoice, DeviceLists, EndKind, EndReason, Progress, Reaction, RosterEntry,
6 6 ShareKind, ShareSource, SpeakingDetector, VideoHub,
7 7 };
8 8 use tokio::sync::mpsc::UnboundedSender;
@@ -16,6 +16,8 @@ pub const MAX_TILES: usize = 9;
16 16 const ORGID_PREFIX: &str = "8:orgid:";
17 17 const WIDE_TILES: usize = 2;
18 18 const MEDIUM_TILES: usize = 4;
19 pub const REACTION_SHOWN: Duration = Duration::from_secs(3);
20 pub const CHAT_OPEN_TILES: usize = 6;
19 21
20 22 pub struct ActiveCall {
21 23 pub id: u64,
@@ -26,6 +28,20 @@ pub struct ActiveCall {
26 28 pub video: Arc<VideoHub>,
27 29 pub pictures: CallPictures,
28 30 pub stage_fullscreen: bool,
31 pub chat_open: bool,
32 }
33
34 impl ActiveCall {
35 pub fn chat_thread(&self) -> Option<&str> {
36 chat_thread(self.model.kind, self.model.meeting_chat.as_deref(), self.conversation_id.as_deref())
37 }
38 }
39
40 pub fn chat_thread<'a>(kind: CallKind, meeting_chat: Option<&'a str>, conversation_id: Option<&'a str>) -> Option<&'a str> {
41 match kind {
42 CallKind::Meeting => meeting_chat.or(conversation_id),
43 CallKind::Test | CallKind::Direct | CallKind::Group => conversation_id,
44 }
29 45 }
30 46
31 47 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -53,6 +69,7 @@ pub struct Tile {
53 69 pub state: TileState,
54 70 pub invited: bool,
55 71 pub has_video: bool,
72 pub hand: Option<u64>,
56 73 }
57 74
58 75 impl Tile {
@@ -65,6 +82,7 @@ impl Tile {
65 82 state: TileState::Invited,
66 83 invited: true,
67 84 has_video: false,
85 hand: None,
68 86 }
69 87 }
70 88 }
@@ -75,15 +93,15 @@ pub struct GridLayout {
75 93 pub hidden: usize,
76 94 }
77 95
78 pub fn grid_layout(others: usize) -> GridLayout {
96 pub fn grid_layout(others: usize, max_tiles: usize) -> GridLayout {
79 97 let total = others + 1;
80 if total <= MAX_TILES {
98 if total <= max_tiles {
81 99 return GridLayout {
82 100 shown_others: others,
83 101 hidden: 0,
84 102 };
85 103 }
86 let shown_others = MAX_TILES - 2;
104 let shown_others = max_tiles - 2;
87 105 GridLayout {
88 106 shown_others,
89 107 hidden: others - shown_others,
@@ -119,6 +137,14 @@ pub fn tile_size(cells: usize) -> TileSize {
119 137 }
120 138 }
121 139
140 #[derive(Debug, Clone, PartialEq, Eq)]
141 pub struct ReactionChip {
142 pub mri: String,
143 pub reaction: Reaction,
144 pub since: Instant,
145 pub serial: u64,
146 }
147
122 148 #[derive(Debug, Clone)]
123 149 pub struct CallModel {
124 150 pub title: String,
@@ -146,6 +172,11 @@ pub struct CallModel {
146 172 pub camera: DeviceChoice,
147 173 pub local_share: Option<String>,
148 174 pub share_sources: Vec<ShareSource>,
175 pub share_sound: bool,
176 pub own_hand: Option<u64>,
177 pub reactions: Vec<ReactionChip>,
178 reaction_serial: u64,
179 pub meeting_chat: Option<String>,
149 180 local_detector: SpeakingDetector,
150 181 remote_detector: SpeakingDetector,
151 182 }
@@ -178,6 +209,11 @@ impl CallModel {
178 209 camera: DeviceChoice::SystemDefault,
179 210 local_share: None,
180 211 share_sources: Vec::new(),
212 share_sound: false,
213 own_hand: None,
214 reactions: Vec::new(),
215 reaction_serial: 0,
216 meeting_chat: None,
181 217 local_detector: SpeakingDetector::default(),
182 218 remote_detector: SpeakingDetector::default(),
183 219 }
@@ -260,8 +296,16 @@ impl CallModel {
260 296 CallUpdate::VideoReady | CallUpdate::Notice(_) => {}
261 297 CallUpdate::Camera(on) => self.camera_on = on,
262 298 CallUpdate::Cameras(cameras) => self.cameras = cameras,
263 CallUpdate::LocalShare(label) => self.local_share = label,
299 CallUpdate::LocalShare(label) => {
300 if label.is_none() {
301 self.share_sound = false;
302 }
303 self.local_share = label;
304 }
264 305 CallUpdate::ShareSources(sources) => self.share_sources = sources,
306 CallUpdate::ShareSound(active) => self.share_sound = active,
307 CallUpdate::Reaction { mri, reaction } => self.note_reaction(mri, reaction, Instant::now()),
308 CallUpdate::MeetingChat(thread) => self.meeting_chat = Some(thread),
265 309 }
266 310 }
267 311
@@ -273,7 +317,46 @@ impl CallModel {
273 317 self.remote_detector.reset();
274 318 }
275 319
320 pub fn note_reaction(&mut self, mri: String, reaction: Reaction, at: Instant) {
321 self.reactions.retain(|chip| chip.mri != mri && at.saturating_duration_since(chip.since) < REACTION_SHOWN);
322 self.reaction_serial += 1;
323 self.reactions.push(ReactionChip { mri, reaction, since: at, serial: self.reaction_serial });
324 }
325
326 pub fn chip_of(&self, mri: &str, now: Instant) -> Option<&ReactionChip> {
327 self.reactions
328 .iter()
329 .find(|chip| chip.mri == mri && now.saturating_duration_since(chip.since) < REACTION_SHOWN)
330 }
331
332 pub fn own_chip(&self, now: Instant) -> Option<&ReactionChip> {
333 self.chip_of(self.own_mri.as_deref()?, now)
334 }
335
336 pub fn hand_position(&self, rank: u64) -> usize {
337 let raised = self.tiles.iter().filter_map(|tile| tile.hand).chain(self.own_hand);
338 1 + raised.filter(|other| *other < rank).count()
339 }
340
341 pub fn can_lower_hands(&self) -> bool {
342 self.can_end_meeting
343 }
344
345 pub fn any_hand_raised(&self) -> bool {
346 self.own_hand.is_some() || self.tiles.iter().any(|tile| tile.hand.is_some())
347 }
348
349 pub fn own_cell_index(&self, remote_cells: usize) -> usize {
350 let Some(own) = self.own_hand else { return remote_cells };
351 let ahead = self.visible_tiles().iter().filter(|tile| tile.hand.is_some_and(|rank| rank < own)).count();
352 ahead.min(remote_cells)
353 }
354
276 355 fn apply_roster(&mut self, entries: &[RosterEntry]) {
356 self.own_hand = entries
357 .iter()
358 .find(|entry| Some(&entry.mri) == self.own_mri.as_ref())
359 .and_then(|entry| entry.hand.as_ref().map(|hand| hand.rank));
277 360 for entry in entries.iter().filter(|entry| Some(&entry.mri) != self.own_mri.as_ref()) {
278 361 let state = if entry.in_lobby { TileState::InLobby } else { TileState::Present };
279 362 match self.tiles.iter_mut().find(|tile| tile.mri == entry.mri) {
@@ -281,6 +364,7 @@ impl CallModel {
281 364 tile.state = state;
282 365 tile.muted = entry.muted;
283 366 tile.has_video = entry.has_video;
367 tile.hand = entry.hand.as_ref().map(|hand| hand.rank);
284 368 if tile.name.is_empty() {
285 369 tile.name = entry.display_name.clone();
286 370 }
@@ -293,6 +377,7 @@ impl CallModel {
293 377 state,
294 378 invited: false,
295 379 has_video: entry.has_video,
380 hand: entry.hand.as_ref().map(|hand| hand.rank),
296 381 }),
297 382 }
298 383 }
@@ -315,17 +400,20 @@ impl CallModel {
315 400
316 401 pub fn visible_tiles(&self) -> Vec<&Tile> {
317 402 let mut tiles: Vec<&Tile> = self.tiles.iter().filter(|tile| tile.state != TileState::InLobby).collect();
318 tiles.sort_by_key(|tile| match tile.state {
319 TileState::Present => 0,
320 TileState::Invited => 1,
321 _ => 2,
403 tiles.sort_by_key(|tile| {
404 let state = match tile.state {
405 TileState::Present => 0,
406 TileState::Invited => 1,
407 _ => 2,
408 };
409 (tile.hand.is_none(), tile.hand.unwrap_or(0), state)
322 410 });
323 411 tiles
324 412 }
325 413
326 414 pub fn strip_tiles(&self) -> Vec<&Tile> {
327 415 let mut tiles = self.visible_tiles();
328 tiles.sort_by_key(|tile| !self.tile_speaking(tile));
416 tiles.sort_by_key(|tile| (tile.hand.is_none(), tile.hand.unwrap_or(0), !self.tile_speaking(tile)));
329 417 tiles
330 418 }
331 419
@@ -400,6 +488,10 @@ impl CallModel {
400 488 self.elapsed(now).map(format_elapsed).unwrap_or_default()
401 489 }
402 490
491 pub fn can_react(&self) -> bool {
492 self.is_live() && !self.lobby
493 }
494
403 495 pub fn can_use_camera(&self) -> bool {
404 496 !self.cameras.is_empty()
405 497 }
@@ -472,6 +564,14 @@ mod tests {
472 564 in_lobby,
473 565 has_video: false,
474 566 sharing: false,
567 hand: None,
568 }
569 }
570
571 fn raised(mri: &str, name: &str, rank: u64) -> RosterEntry {
572 RosterEntry {
573 hand: Some(calling::RaisedHand { state_id: format!("s-{rank}"), rank }),
574 ..entry(mri, name, false, false)
475 575 }
476 576 }
477 577
@@ -660,10 +760,16 @@ mod tests {
660 760
661 761 #[test]
662 762 fn more_than_nine_cells_collapse_into_a_plus_n_tile() {
663 assert_eq!(grid_layout(0), GridLayout { shown_others: 0, hidden: 0 });
664 assert_eq!(grid_layout(8), GridLayout { shown_others: 8, hidden: 0 });
665 assert_eq!(grid_layout(9), GridLayout { shown_others: 7, hidden: 2 });
666 assert_eq!(grid_layout(30), GridLayout { shown_others: 7, hidden: 23 });
763 assert_eq!(grid_layout(0, MAX_TILES), GridLayout { shown_others: 0, hidden: 0 });
764 assert_eq!(grid_layout(8, MAX_TILES), GridLayout { shown_others: 8, hidden: 0 });
765 assert_eq!(grid_layout(9, MAX_TILES), GridLayout { shown_others: 7, hidden: 2 });
766 assert_eq!(grid_layout(30, MAX_TILES), GridLayout { shown_others: 7, hidden: 23 });
767 }
768
769 #[test]
770 fn an_open_chat_panel_leaves_room_for_fewer_tiles() {
771 assert_eq!(grid_layout(5, CHAT_OPEN_TILES), GridLayout { shown_others: 5, hidden: 0 });
772 assert_eq!(grid_layout(6, CHAT_OPEN_TILES), GridLayout { shown_others: 4, hidden: 2 });
667 773 }
668 774
669 775 #[test]
@@ -712,4 +818,75 @@ mod tests {
712 818 let names: Vec<&str> = model.visible_tiles().iter().map(|tile| tile.name.as_str()).collect();
713 819 assert_eq!(names, vec!["Cy", "Bea"]);
714 820 }
821
822 #[test]
823 fn raised_hands_get_queue_positions_by_raise_time_and_sort_first() {
824 let mut model = meeting_with_me();
825 model.apply(CallUpdate::Roster(vec![
826 entry("8:orgid:a", "Ana", false, false),
827 raised("8:orgid:b", "Bo", 9),
828 raised("8:orgid:c", "Cy", 4),
829 raised("8:orgid:me", "Me", 6),
830 ]));
831 assert_eq!(model.own_hand, Some(6));
832 assert!(model.any_hand_raised());
833 let names: Vec<&str> = model.visible_tiles().iter().map(|tile| tile.name.as_str()).collect();
834 assert_eq!(names, vec!["Cy", "Bo", "Ana"]);
835 let positions: Vec<usize> = [4, 6, 9].into_iter().map(|rank| model.hand_position(rank)).collect();
836 assert_eq!(positions, vec![1, 2, 3]);
837 assert_eq!(model.own_cell_index(3), 1);
838 let strip: Vec<&str> = model.strip_tiles().iter().map(|tile| tile.name.as_str()).collect();
839 assert_eq!(strip, vec!["Cy", "Bo", "Ana"]);
840 }
841
842 #[test]
843 fn lowering_clears_the_hand_everywhere() {
844 let mut model = meeting_with_me();
845 model.apply(CallUpdate::Roster(vec![raised("8:orgid:a", "Ana", 1), raised("8:orgid:me", "Me", 2)]));
846 model.apply(CallUpdate::Roster(vec![entry("8:orgid:a", "Ana", false, false), entry("8:orgid:me", "Me", false, false)]));
847 assert!(!model.any_hand_raised());
848 assert_eq!(model.own_cell_index(1), 1);
849 }
850
851 #[test]
852 fn only_organizers_may_lower_hands() {
853 assert!(!CallModel::meeting("Standup", false).can_lower_hands());
854 assert!(CallModel::meeting("Standup", true).can_lower_hands());
855 }
856
857 #[test]
858 fn a_reaction_shows_for_three_seconds_on_its_sender_and_the_latest_wins() {
859 let mut model = meeting_with_me();
860 let start = Instant::now();
861 model.note_reaction("8:orgid:a".into(), Reaction::Heart, start);
862 model.note_reaction("8:orgid:me".into(), Reaction::Like, start);
863 let reaction_at = |model: &CallModel, mri: &str, seconds: u64| {
864 model.chip_of(mri, start + Duration::from_secs(seconds)).map(|chip| chip.reaction)
865 };
866 assert_eq!(reaction_at(&model, "8:orgid:a", 2), Some(Reaction::Heart));
867 assert_eq!(model.own_chip(start + Duration::from_secs(2)).map(|chip| chip.reaction), Some(Reaction::Like));
868 assert_eq!(reaction_at(&model, "8:orgid:a", 3), None);
869 model.note_reaction("8:orgid:a".into(), Reaction::Laugh, start + Duration::from_secs(1));
870 assert_eq!(reaction_at(&model, "8:orgid:a", 2), Some(Reaction::Laugh));
871 assert_eq!(model.reactions.len(), 2);
872 }
873
874 #[test]
875 fn the_chat_panel_picks_the_meeting_thread_or_the_call_chat() {
876 assert_eq!(chat_thread(CallKind::Meeting, Some("19:meeting_x"), Some("19:list")), Some("19:meeting_x"));
877 assert_eq!(chat_thread(CallKind::Meeting, None, Some("19:list")), Some("19:list"));
878 assert_eq!(chat_thread(CallKind::Direct, Some("19:meeting_x"), Some("19:dm")), Some("19:dm"));
879 assert_eq!(chat_thread(CallKind::Group, None, Some("19:group")), Some("19:group"));
880 assert_eq!(chat_thread(CallKind::Test, None, None), None);
881 }
882
883 #[test]
884 fn computer_sound_follows_the_share() {
885 let mut model = connected_model();
886 model.apply(CallUpdate::LocalShare(Some("Screen".into())));
887 model.apply(CallUpdate::ShareSound(true));
888 assert!(model.share_sound);
889 model.apply(CallUpdate::LocalShare(None));
890 assert!(!model.share_sound);
891 }
715 892 }
@@ -2,7 +2,7 @@ use std::sync::Arc;
2use std::time::{Duration, Instant};
2use std::time::{Duration, Instant};
3
3
4use calling::{
4use calling::{
5 CallCommand, CallState, CallUpdate, CameraDevice, DeviceChoice, DeviceLists, EndKind, EndReason, Progress, RosterEntry,
5 CallCommand, CallState, CallUpdate, CameraDevice, DeviceChoice, DeviceLists, EndKind, EndReason, Progress, Reaction, RosterEntry,
6 ShareKind, ShareSource, SpeakingDetector, VideoHub,
6 ShareKind, ShareSource, SpeakingDetector, VideoHub,
7};
7};
8use tokio::sync::mpsc::UnboundedSender;
8use tokio::sync::mpsc::UnboundedSender;
@@ -16,6 +16,8 @@ pub const MAX_TILES: usize = 9;
16const ORGID_PREFIX: &str = "8:orgid:";
16const ORGID_PREFIX: &str = "8:orgid:";
17const WIDE_TILES: usize = 2;
17const WIDE_TILES: usize = 2;
18const MEDIUM_TILES: usize = 4;
18const MEDIUM_TILES: usize = 4;
19pub const REACTION_SHOWN: Duration = Duration::from_secs(3);
20pub const CHAT_OPEN_TILES: usize = 6;
19
21
20pub struct ActiveCall {
22pub struct ActiveCall {
21 pub id: u64,
23 pub id: u64,
@@ -26,6 +28,20 @@ pub struct ActiveCall {
26 pub video: Arc<VideoHub>,
28 pub video: Arc<VideoHub>,
27 pub pictures: CallPictures,
29 pub pictures: CallPictures,
28 pub stage_fullscreen: bool,
30 pub stage_fullscreen: bool,
31 pub chat_open: bool,
32}
33
34impl ActiveCall {
35 pub fn chat_thread(&self) -> Option<&str> {
36 chat_thread(self.model.kind, self.model.meeting_chat.as_deref(), self.conversation_id.as_deref())
37 }
38}
39
40pub fn chat_thread<'a>(kind: CallKind, meeting_chat: Option<&'a str>, conversation_id: Option<&'a str>) -> Option<&'a str> {
41 match kind {
42 CallKind::Meeting => meeting_chat.or(conversation_id),
43 CallKind::Test | CallKind::Direct | CallKind::Group => conversation_id,
44 }
29}
45}
30
46
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -53,6 +69,7 @@ pub struct Tile {
53 pub state: TileState,
69 pub state: TileState,
54 pub invited: bool,
70 pub invited: bool,
55 pub has_video: bool,
71 pub has_video: bool,
72 pub hand: Option<u64>,
56}
73}
57
74
58impl Tile {
75impl Tile {
@@ -65,6 +82,7 @@ impl Tile {
65 state: TileState::Invited,
82 state: TileState::Invited,
66 invited: true,
83 invited: true,
67 has_video: false,
84 has_video: false,
85 hand: None,
68 }
86 }
69 }
87 }
70}
88}
@@ -75,15 +93,15 @@ pub struct GridLayout {
75 pub hidden: usize,
93 pub hidden: usize,
76}
94}
77
95
78pub fn grid_layout(others: usize) -> GridLayout {
96pub fn grid_layout(others: usize, max_tiles: usize) -> GridLayout {
79 let total = others + 1;
97 let total = others + 1;
80 if total <= MAX_TILES {
98 if total <= max_tiles {
81 return GridLayout {
99 return GridLayout {
82 shown_others: others,
100 shown_others: others,
83 hidden: 0,
101 hidden: 0,
84 };
102 };
85 }
103 }
86 let shown_others = MAX_TILES - 2;
104 let shown_others = max_tiles - 2;
87 GridLayout {
105 GridLayout {
88 shown_others,
106 shown_others,
89 hidden: others - shown_others,
107 hidden: others - shown_others,
@@ -119,6 +137,14 @@ pub fn tile_size(cells: usize) -> TileSize {
119 }
137 }
120}
138}
121
139
140#[derive(Debug, Clone, PartialEq, Eq)]
141pub struct ReactionChip {
142 pub mri: String,
143 pub reaction: Reaction,
144 pub since: Instant,
145 pub serial: u64,
146}
147
122#[derive(Debug, Clone)]
148#[derive(Debug, Clone)]
123pub struct CallModel {
149pub struct CallModel {
124 pub title: String,
150 pub title: String,
@@ -146,6 +172,11 @@ pub struct CallModel {
146 pub camera: DeviceChoice,
172 pub camera: DeviceChoice,
147 pub local_share: Option<String>,
173 pub local_share: Option<String>,
148 pub share_sources: Vec<ShareSource>,
174 pub share_sources: Vec<ShareSource>,
175 pub share_sound: bool,
176 pub own_hand: Option<u64>,
177 pub reactions: Vec<ReactionChip>,
178 reaction_serial: u64,
179 pub meeting_chat: Option<String>,
149 local_detector: SpeakingDetector,
180 local_detector: SpeakingDetector,
150 remote_detector: SpeakingDetector,
181 remote_detector: SpeakingDetector,
151}
182}
@@ -178,6 +209,11 @@ impl CallModel {
178 camera: DeviceChoice::SystemDefault,
209 camera: DeviceChoice::SystemDefault,
179 local_share: None,
210 local_share: None,
180 share_sources: Vec::new(),
211 share_sources: Vec::new(),
212 share_sound: false,
213 own_hand: None,
214 reactions: Vec::new(),
215 reaction_serial: 0,
216 meeting_chat: None,
181 local_detector: SpeakingDetector::default(),
217 local_detector: SpeakingDetector::default(),
182 remote_detector: SpeakingDetector::default(),
218 remote_detector: SpeakingDetector::default(),
183 }
219 }
@@ -260,8 +296,16 @@ impl CallModel {
260 CallUpdate::VideoReady | CallUpdate::Notice(_) => {}
296 CallUpdate::VideoReady | CallUpdate::Notice(_) => {}
261 CallUpdate::Camera(on) => self.camera_on = on,
297 CallUpdate::Camera(on) => self.camera_on = on,
262 CallUpdate::Cameras(cameras) => self.cameras = cameras,
298 CallUpdate::Cameras(cameras) => self.cameras = cameras,
263 CallUpdate::LocalShare(label) => self.local_share = label,
299 CallUpdate::LocalShare(label) => {
300 if label.is_none() {
301 self.share_sound = false;
302 }
303 self.local_share = label;
304 }
264 CallUpdate::ShareSources(sources) => self.share_sources = sources,
305 CallUpdate::ShareSources(sources) => self.share_sources = sources,
306 CallUpdate::ShareSound(active) => self.share_sound = active,
307 CallUpdate::Reaction { mri, reaction } => self.note_reaction(mri, reaction, Instant::now()),
308 CallUpdate::MeetingChat(thread) => self.meeting_chat = Some(thread),
265 }
309 }
266 }
310 }
267
311
@@ -273,7 +317,46 @@ impl CallModel {
273 self.remote_detector.reset();
317 self.remote_detector.reset();
274 }
318 }
275
319
320 pub fn note_reaction(&mut self, mri: String, reaction: Reaction, at: Instant) {
321 self.reactions.retain(|chip| chip.mri != mri && at.saturating_duration_since(chip.since) < REACTION_SHOWN);
322 self.reaction_serial += 1;
323 self.reactions.push(ReactionChip { mri, reaction, since: at, serial: self.reaction_serial });
324 }
325
326 pub fn chip_of(&self, mri: &str, now: Instant) -> Option<&ReactionChip> {
327 self.reactions
328 .iter()
329 .find(|chip| chip.mri == mri && now.saturating_duration_since(chip.since) < REACTION_SHOWN)
330 }
331
332 pub fn own_chip(&self, now: Instant) -> Option<&ReactionChip> {
333 self.chip_of(self.own_mri.as_deref()?, now)
334 }
335
336 pub fn hand_position(&self, rank: u64) -> usize {
337 let raised = self.tiles.iter().filter_map(|tile| tile.hand).chain(self.own_hand);
338 1 + raised.filter(|other| *other < rank).count()
339 }
340
341 pub fn can_lower_hands(&self) -> bool {
342 self.can_end_meeting
343 }
344
345 pub fn any_hand_raised(&self) -> bool {
346 self.own_hand.is_some() || self.tiles.iter().any(|tile| tile.hand.is_some())
347 }
348
349 pub fn own_cell_index(&self, remote_cells: usize) -> usize {
350 let Some(own) = self.own_hand else { return remote_cells };
351 let ahead = self.visible_tiles().iter().filter(|tile| tile.hand.is_some_and(|rank| rank < own)).count();
352 ahead.min(remote_cells)
353 }
354
276 fn apply_roster(&mut self, entries: &[RosterEntry]) {
355 fn apply_roster(&mut self, entries: &[RosterEntry]) {
356 self.own_hand = entries
357 .iter()
358 .find(|entry| Some(&entry.mri) == self.own_mri.as_ref())
359 .and_then(|entry| entry.hand.as_ref().map(|hand| hand.rank));
277 for entry in entries.iter().filter(|entry| Some(&entry.mri) != self.own_mri.as_ref()) {
360 for entry in entries.iter().filter(|entry| Some(&entry.mri) != self.own_mri.as_ref()) {
278 let state = if entry.in_lobby { TileState::InLobby } else { TileState::Present };
361 let state = if entry.in_lobby { TileState::InLobby } else { TileState::Present };
279 match self.tiles.iter_mut().find(|tile| tile.mri == entry.mri) {
362 match self.tiles.iter_mut().find(|tile| tile.mri == entry.mri) {
@@ -281,6 +364,7 @@ impl CallModel {
281 tile.state = state;
364 tile.state = state;
282 tile.muted = entry.muted;
365 tile.muted = entry.muted;
283 tile.has_video = entry.has_video;
366 tile.has_video = entry.has_video;
367 tile.hand = entry.hand.as_ref().map(|hand| hand.rank);
284 if tile.name.is_empty() {
368 if tile.name.is_empty() {
285 tile.name = entry.display_name.clone();
369 tile.name = entry.display_name.clone();
286 }
370 }
@@ -293,6 +377,7 @@ impl CallModel {
293 state,
377 state,
294 invited: false,
378 invited: false,
295 has_video: entry.has_video,
379 has_video: entry.has_video,
380 hand: entry.hand.as_ref().map(|hand| hand.rank),
296 }),
381 }),
297 }
382 }
298 }
383 }
@@ -315,17 +400,20 @@ impl CallModel {
315
400
316 pub fn visible_tiles(&self) -> Vec<&Tile> {
401 pub fn visible_tiles(&self) -> Vec<&Tile> {
317 let mut tiles: Vec<&Tile> = self.tiles.iter().filter(|tile| tile.state != TileState::InLobby).collect();
402 let mut tiles: Vec<&Tile> = self.tiles.iter().filter(|tile| tile.state != TileState::InLobby).collect();
318 tiles.sort_by_key(|tile| match tile.state {
403 tiles.sort_by_key(|tile| {
319 TileState::Present => 0,
404 let state = match tile.state {
320 TileState::Invited => 1,
405 TileState::Present => 0,
321 _ => 2,
406 TileState::Invited => 1,
407 _ => 2,
408 };
409 (tile.hand.is_none(), tile.hand.unwrap_or(0), state)
322 });
410 });
323 tiles
411 tiles
324 }
412 }
325
413
326 pub fn strip_tiles(&self) -> Vec<&Tile> {
414 pub fn strip_tiles(&self) -> Vec<&Tile> {
327 let mut tiles = self.visible_tiles();
415 let mut tiles = self.visible_tiles();
328 tiles.sort_by_key(|tile| !self.tile_speaking(tile));
416 tiles.sort_by_key(|tile| (tile.hand.is_none(), tile.hand.unwrap_or(0), !self.tile_speaking(tile)));
329 tiles
417 tiles
330 }
418 }
331
419
@@ -400,6 +488,10 @@ impl CallModel {
400 self.elapsed(now).map(format_elapsed).unwrap_or_default()
488 self.elapsed(now).map(format_elapsed).unwrap_or_default()
401 }
489 }
402
490
491 pub fn can_react(&self) -> bool {
492 self.is_live() && !self.lobby
493 }
494
403 pub fn can_use_camera(&self) -> bool {
495 pub fn can_use_camera(&self) -> bool {
404 !self.cameras.is_empty()
496 !self.cameras.is_empty()
405 }
497 }
@@ -472,6 +564,14 @@ mod tests {
472 in_lobby,
564 in_lobby,
473 has_video: false,
565 has_video: false,
474 sharing: false,
566 sharing: false,
567 hand: None,
568 }
569 }
570
571 fn raised(mri: &str, name: &str, rank: u64) -> RosterEntry {
572 RosterEntry {
573 hand: Some(calling::RaisedHand { state_id: format!("s-{rank}"), rank }),
574 ..entry(mri, name, false, false)
475 }
575 }
476 }
576 }
477
577
@@ -660,10 +760,16 @@ mod tests {
660
760
661 #[test]
761 #[test]
662 fn more_than_nine_cells_collapse_into_a_plus_n_tile() {
762 fn more_than_nine_cells_collapse_into_a_plus_n_tile() {
663 assert_eq!(grid_layout(0), GridLayout { shown_others: 0, hidden: 0 });
763 assert_eq!(grid_layout(0, MAX_TILES), GridLayout { shown_others: 0, hidden: 0 });
664 assert_eq!(grid_layout(8), GridLayout { shown_others: 8, hidden: 0 });
764 assert_eq!(grid_layout(8, MAX_TILES), GridLayout { shown_others: 8, hidden: 0 });
665 assert_eq!(grid_layout(9), GridLayout { shown_others: 7, hidden: 2 });
765 assert_eq!(grid_layout(9, MAX_TILES), GridLayout { shown_others: 7, hidden: 2 });
666 assert_eq!(grid_layout(30), GridLayout { shown_others: 7, hidden: 23 });
766 assert_eq!(grid_layout(30, MAX_TILES), GridLayout { shown_others: 7, hidden: 23 });
767 }
768
769 #[test]
770 fn an_open_chat_panel_leaves_room_for_fewer_tiles() {
771 assert_eq!(grid_layout(5, CHAT_OPEN_TILES), GridLayout { shown_others: 5, hidden: 0 });
772 assert_eq!(grid_layout(6, CHAT_OPEN_TILES), GridLayout { shown_others: 4, hidden: 2 });
667 }
773 }
668
774
669 #[test]
775 #[test]
@@ -712,4 +818,75 @@ mod tests {
712 let names: Vec<&str> = model.visible_tiles().iter().map(|tile| tile.name.as_str()).collect();
818 let names: Vec<&str> = model.visible_tiles().iter().map(|tile| tile.name.as_str()).collect();
713 assert_eq!(names, vec!["Cy", "Bea"]);
819 assert_eq!(names, vec!["Cy", "Bea"]);
714 }
820 }
821
822 #[test]
823 fn raised_hands_get_queue_positions_by_raise_time_and_sort_first() {
824 let mut model = meeting_with_me();
825 model.apply(CallUpdate::Roster(vec![
826 entry("8:orgid:a", "Ana", false, false),
827 raised("8:orgid:b", "Bo", 9),
828 raised("8:orgid:c", "Cy", 4),
829 raised("8:orgid:me", "Me", 6),
830 ]));
831 assert_eq!(model.own_hand, Some(6));
832 assert!(model.any_hand_raised());
833 let names: Vec<&str> = model.visible_tiles().iter().map(|tile| tile.name.as_str()).collect();
834 assert_eq!(names, vec!["Cy", "Bo", "Ana"]);
835 let positions: Vec<usize> = [4, 6, 9].into_iter().map(|rank| model.hand_position(rank)).collect();
836 assert_eq!(positions, vec![1, 2, 3]);
837 assert_eq!(model.own_cell_index(3), 1);
838 let strip: Vec<&str> = model.strip_tiles().iter().map(|tile| tile.name.as_str()).collect();
839 assert_eq!(strip, vec!["Cy", "Bo", "Ana"]);
840 }
841
842 #[test]
843 fn lowering_clears_the_hand_everywhere() {
844 let mut model = meeting_with_me();
845 model.apply(CallUpdate::Roster(vec![raised("8:orgid:a", "Ana", 1), raised("8:orgid:me", "Me", 2)]));
846 model.apply(CallUpdate::Roster(vec![entry("8:orgid:a", "Ana", false, false), entry("8:orgid:me", "Me", false, false)]));
847 assert!(!model.any_hand_raised());
848 assert_eq!(model.own_cell_index(1), 1);
849 }
850
851 #[test]
852 fn only_organizers_may_lower_hands() {
853 assert!(!CallModel::meeting("Standup", false).can_lower_hands());
854 assert!(CallModel::meeting("Standup", true).can_lower_hands());
855 }
856
857 #[test]
858 fn a_reaction_shows_for_three_seconds_on_its_sender_and_the_latest_wins() {
859 let mut model = meeting_with_me();
860 let start = Instant::now();
861 model.note_reaction("8:orgid:a".into(), Reaction::Heart, start);
862 model.note_reaction("8:orgid:me".into(), Reaction::Like, start);
863 let reaction_at = |model: &CallModel, mri: &str, seconds: u64| {
864 model.chip_of(mri, start + Duration::from_secs(seconds)).map(|chip| chip.reaction)
865 };
866 assert_eq!(reaction_at(&model, "8:orgid:a", 2), Some(Reaction::Heart));
867 assert_eq!(model.own_chip(start + Duration::from_secs(2)).map(|chip| chip.reaction), Some(Reaction::Like));
868 assert_eq!(reaction_at(&model, "8:orgid:a", 3), None);
869 model.note_reaction("8:orgid:a".into(), Reaction::Laugh, start + Duration::from_secs(1));
870 assert_eq!(reaction_at(&model, "8:orgid:a", 2), Some(Reaction::Laugh));
871 assert_eq!(model.reactions.len(), 2);
872 }
873
874 #[test]
875 fn the_chat_panel_picks_the_meeting_thread_or_the_call_chat() {
876 assert_eq!(chat_thread(CallKind::Meeting, Some("19:meeting_x"), Some("19:list")), Some("19:meeting_x"));
877 assert_eq!(chat_thread(CallKind::Meeting, None, Some("19:list")), Some("19:list"));
878 assert_eq!(chat_thread(CallKind::Direct, Some("19:meeting_x"), Some("19:dm")), Some("19:dm"));
879 assert_eq!(chat_thread(CallKind::Group, None, Some("19:group")), Some("19:group"));
880 assert_eq!(chat_thread(CallKind::Test, None, None), None);
881 }
882
883 #[test]
884 fn computer_sound_follows_the_share() {
885 let mut model = connected_model();
886 model.apply(CallUpdate::LocalShare(Some("Screen".into())));
887 model.apply(CallUpdate::ShareSound(true));
888 assert!(model.share_sound);
889 model.apply(CallUpdate::LocalShare(None));
890 assert!(!model.share_sound);
891 }
715}
892}
crates/app/src/views/call_view.rs +301 −38
@@ -1,12 +1,14 @@
1 1 use std::sync::Arc;
2 2 use std::time::{Duration, Instant};
3 3
4 use calling::{DeviceEntry, VideoKey};
4 use calling::{DeviceEntry, Reaction, VideoKey};
5 5 use gpui_kit::assets::IconName;
6 6 use gpui_kit::component::{
7 7 button::{Button, ButtonVariants as _},
8 8 h_flex,
9 menu::{DropdownMenu as _, PopupMenu, PopupMenuItem},
9 menu::{ContextMenuExt as _, DropdownMenu as _, PopupMenu, PopupMenuItem},
10 popover::Popover,
11 switch::Switch,
10 12 tooltip::Tooltip,
11 13 v_flex,
12 14 };
@@ -15,10 +17,13 @@ use gpui_kit::*;
15 17
16 18 use super::avatar::person_avatar;
17 19 use super::call_stage::render_stage;
18 use super::widgets::icon;
20 use super::conversation::ConversationView;
21 use super::widgets::{count_badge, icon, symbol};
19 22 use crate::app_state::AppState;
20 23 use crate::call::TileSize;
21 use crate::call::{CallKind, CallModel, GridLayout, Tile, TileState, grid_layout, tile_size};
24 use crate::call::{CHAT_OPEN_TILES, CallKind, CallModel, GridLayout, MAX_TILES, Tile, TileState, grid_layout, tile_size};
25 use crate::call::REACTION_SHOWN;
26 use crate::rows::reaction_glyph as chat_reaction_glyph;
22 27 use crate::theme;
23 28
24 29 const HEADER_HEIGHT: f32 = 60.;
@@ -47,6 +52,75 @@ pub const NO_WINDOWS_HINT: &str = "No windows found";
47 52 const BANNER_HEIGHT: f32 = 40.;
48 53 const MAX_WINDOW_ITEMS: usize = 12;
49 54 pub const LOBBY_TEXT: &str = "Waiting in the lobby...";
55 pub const CHAT_PANEL_WIDTH: f32 = 320.;
56 const CHAT_HEADER_HEIGHT: f32 = 48.;
57 const HAND_GLYPH: &str = "\u{270B}";
58 const REACTION_RISE: f32 = 24.;
59 const REACTION_FADE_FROM: f32 = 0.75;
60 const REACTION_CELL: f32 = 40.;
61 const SHARE_SOUND_LABEL: &str = "Include computer sound";
62
63 pub fn reaction_glyph(reaction: Reaction) -> String {
64 match reaction {
65 Reaction::Applause => "\u{1F44F}".to_owned(),
66 other => chat_reaction_glyph(other.name()),
67 }
68 }
69
70 #[derive(Default)]
71 struct TileExtras {
72 hand: Option<usize>,
73 reaction: Option<(Reaction, u64)>,
74 }
75
76 fn hand_badge(position: usize) -> Div {
77 h_flex()
78 .absolute()
79 .top(px(10.))
80 .left(px(10.))
81 .h(px(24.))
82 .px(px(8.))
83 .gap(px(4.))
84 .items_center()
85 .rounded_full()
86 .bg(theme::amber())
87 .text_color(hsla(0., 0., 0.08, 1.))
88 .text_size(px(12.))
89 .font_weight(FontWeight::SEMIBOLD)
90 .child(format!("Hand {position}"))
91 }
92
93 fn reaction_chip(reaction: Reaction, serial: u64) -> AnyElement {
94 div()
95 .absolute()
96 .right(px(12.))
97 .bottom(px(34.))
98 .size(px(36.))
99 .flex()
100 .items_center()
101 .justify_center()
102 .rounded_full()
103 .bg(theme::surface_raised())
104 .border_1()
105 .border_color(theme::border_strong())
106 .text_size(px(20.))
107 .child(reaction_glyph(reaction))
108 .with_animation(
109 ("call-reaction", serial as usize),
110 Animation::new(REACTION_SHOWN),
111 |chip, delta| {
112 let fade = ((delta - REACTION_FADE_FROM) / (1. - REACTION_FADE_FROM)).clamp(0., 1.);
113 chip.bottom(px(34. + REACTION_RISE * delta)).opacity(1. - fade)
114 },
115 )
116 .into_any_element()
117 }
118
119 fn tile_overlays(extras: &TileExtras) -> Vec<AnyElement> {
120 let hand = extras.hand.map(|position| hand_badge(position).into_any_element());
121 let reaction = extras.reaction.map(|(reaction, serial)| reaction_chip(reaction, serial));
122 hand.into_iter().chain(reaction).collect()
123 }
50 124
51 125 pub fn status_line(model: &CallModel, now: Instant) -> (String, Hsla) {
52 126 if model.lobby {
@@ -101,7 +175,7 @@ fn mute_badge() -> Div {
101 175 .child(icon(IconName::MicOff, 13., theme::white()))
102 176 }
103 177
104 fn video_tile(size: TileSize, image: Arc<RenderImage>, name: &str, speaking: bool, muted: bool) -> Div {
178 fn video_tile(size: TileSize, image: Arc<RenderImage>, name: &str, speaking: bool, muted: bool, extras: &TileExtras) -> Div {
105 179 div()
106 180 .relative()
107 181 .w(px(size.width))
@@ -135,6 +209,7 @@ fn video_tile(size: TileSize, image: Arc<RenderImage>, name: &str, speaking: boo
135 209 .child(name.to_owned()),
136 210 )
137 211 .when(muted, |tile| tile.child(mute_badge()))
212 .children(tile_overlays(extras))
138 213 }
139 214
140 215 fn tile(
@@ -144,6 +219,7 @@ fn tile(
144 219 speaking: bool,
145 220 muted: bool,
146 221 caption: Option<AnyElement>,
222 extras: &TileExtras,
147 223 ) -> Div {
148 224 let badge = div()
149 225 .absolute()
@@ -184,6 +260,7 @@ fn tile(
184 260 .children(caption),
185 261 )
186 262 .when(muted, |tile| tile.child(badge))
263 .children(tile_overlays(extras))
187 264 }
188 265
189 266 fn overflow_tile(size: TileSize, hidden: usize) -> Div {
@@ -205,7 +282,7 @@ fn overflow_tile(size: TileSize, hidden: usize) -> Div {
205 282 )
206 283 }
207 284
208 fn round_control(id: &'static str, glyph: IconName, background: Hsla, foreground: Hsla) -> Stateful<Div> {
285 fn control_shell(id: &'static str, background: Hsla) -> Stateful<Div> {
209 286 div()
210 287 .id(id)
211 288 .size(px(CONTROL_SIZE))
@@ -217,7 +294,10 @@ fn round_control(id: &'static str, glyph: IconName, background: Hsla, foreground
217 294 .bg(background)
218 295 .cursor_pointer()
219 296 .hover(|button| button.opacity(0.85))
220 .child(icon(glyph, CONTROL_ICON, foreground))
297 }
298
299 fn round_control(id: &'static str, glyph: IconName, background: Hsla, foreground: Hsla) -> Stateful<Div> {
300 control_shell(id, background).child(icon(glyph, CONTROL_ICON, foreground))
221 301 }
222 302
223 303 pub fn mute_button(app: &Entity<AppState>, model: &CallModel, id: &'static str, size: f32) -> Stateful<Div> {
@@ -286,10 +366,25 @@ fn camera_button(app: &Entity<AppState>, model: &CallModel) -> Stateful<Div> {
286 366 })
287 367 }
288 368
289 fn share_items(popup: PopupMenu, app: &Entity<AppState>, model: &CallModel) -> PopupMenu {
369 fn sound_switch_item(app: &Entity<AppState>, sound: bool) -> PopupMenuItem {
370 let app = app.clone();
371 PopupMenuItem::element(move |_, _| {
372 h_flex()
373 .id("call-share-sound-row")
374 .w_full()
375 .gap(px(16.))
376 .items_center()
377 .justify_between()
378 .child(SHARE_SOUND_LABEL)
379 .child(Switch::new("call-share-sound").checked(sound))
380 })
381 .on_click(move |_, _, cx| app.update(cx, |state, cx| state.set_call_share_sound(!sound, cx)))
382 }
383
384 fn share_items(popup: PopupMenu, app: &Entity<AppState>, model: &CallModel, sound: bool) -> PopupMenu {
290 385 let screens = model.screens();
291 386 let single_screen = screens.len() == 1;
292 let mut popup = popup.min_w(px(MENU_WIDTH));
387 let mut popup = popup.min_w(px(MENU_WIDTH)).item(sound_switch_item(app, sound)).separator();
293 388 for (index, source) in screens.into_iter().enumerate() {
294 389 let label = if single_screen { "Share entire screen".to_owned() } else { format!("Share screen {}", index + 1) };
295 390 let source = source.clone();
@@ -318,7 +413,7 @@ fn share_items(popup: PopupMenu, app: &Entity<AppState>, model: &CallModel) -> P
318 413 popup
319 414 }
320 415
321 fn share_button(app: &Entity<AppState>, model: &CallModel) -> AnyElement {
416 fn share_button(app: &Entity<AppState>, model: &CallModel, sound: bool) -> AnyElement {
322 417 if model.local_share.is_some() {
323 418 let app = app.clone();
324 419 return round_control("call-share-stop", IconName::ScreenShareOff, theme::accent(), theme::on_accent())
@@ -345,12 +440,13 @@ fn share_button(app: &Entity<AppState>, model: &CallModel) -> AnyElement {
345 440 .size(px(CONTROL_SIZE))
346 441 .rounded_full()
347 442 .child(face)
348 .dropdown_menu_with_anchor(Anchor::BottomLeft, move |popup, _, _| share_items(popup, &app, &model))
443 .dropdown_menu_with_anchor(Anchor::BottomLeft, move |popup, _, _| share_items(popup, &app, &model, sound))
349 444 .into_any_element()
350 445 }
351 446
352 fn sharing_banner(app: &Entity<AppState>, model: &CallModel) -> Option<AnyElement> {
447 fn sharing_banner(app: &Entity<AppState>, model: &CallModel, sound: bool) -> Option<AnyElement> {
353 448 let label = model.local_share.as_ref()?;
449 let sound_app = app.clone();
354 450 let app = app.clone();
355 451 Some(
356 452 h_flex()
@@ -368,6 +464,21 @@ fn sharing_banner(app: &Entity<AppState>, model: &CallModel) -> Option<AnyElemen
368 464 .font_weight(FontWeight::SEMIBOLD)
369 465 .child(icon(IconName::ScreenShare, 16., theme::on_accent()))
370 466 .child(format!("You are sharing: {label}"))
467 .child(
468 div()
469 .id("call-sharing-sound")
470 .h(px(26.))
471 .px(px(12.))
472 .flex()
473 .items_center()
474 .rounded_full()
475 .border_1()
476 .border_color(theme::on_accent())
477 .cursor_pointer()
478 .hover(|button| button.opacity(0.9))
479 .child(if sound { "Computer sound on" } else { "Computer sound off" })
480 .on_click(move |_, _, cx| sound_app.update(cx, |state, cx| state.set_call_share_sound(!sound, cx))),
481 )
371 482 .child(
372 483 div()
373 484 .id("call-sharing-stop")
@@ -387,17 +498,80 @@ fn sharing_banner(app: &Entity<AppState>, model: &CallModel) -> Option<AnyElemen
387 498 )
388 499 }
389 500
390 fn chat_button(app: &Entity<AppState>) -> Stateful<Div> {
501 fn chat_button(app: &Entity<AppState>, open: bool, unread: u32) -> Stateful<Div> {
391 502 let app = app.clone();
392 round_control("call-chat", IconName::MessageCircle, theme::surface_raised(), theme::text())
393 .tooltip(|window, cx| Tooltip::new("Open the chat").build(window, cx))
394 .on_click(move |_, _, cx| app.update(cx, |state, cx| state.open_call_chat(cx)))
503 let (background, foreground) = if open {
504 (theme::accent(), theme::on_accent())
505 } else {
506 (theme::surface_raised(), theme::text())
507 };
508 round_control("call-chat", IconName::MessageCircle, background, foreground)
509 .relative()
510 .tooltip(move |window, cx| Tooltip::new(if open { "Close the chat" } else { "Open the chat" }).build(window, cx))
511 .when(unread > 0, |button| {
512 button.child(div().absolute().top(px(-4.)).right(px(-4.)).child(count_badge(unread, false)))
513 })
514 .on_click(move |_, _, cx| app.update(cx, |state, cx| state.toggle_call_chat(cx)))
515 }
516
517 fn hand_button(app: &Entity<AppState>, model: &CallModel) -> Stateful<Div> {
518 let raised = model.own_hand.is_some();
519 let background = if raised { theme::accent() } else { theme::surface_raised() };
520 let button = control_shell("call-hand", background).child(div().text_size(px(CONTROL_ICON)).child(HAND_GLYPH));
521 let tooltip = if raised { "Lower hand" } else { "Raise hand" };
522 let button = button.tooltip(move |window, cx| Tooltip::new(tooltip).build(window, cx));
523 if !model.can_react() {
524 return button.opacity(DISABLED_OPACITY).cursor_default();
525 }
526 let app = app.clone();
527 button.on_click(move |_, _, cx| {
528 cx.stop_propagation();
529 app.update(cx, |state, cx| state.toggle_call_hand(cx));
530 })
531 }
532
533 fn reactions_button(app: &Entity<AppState>, model: &CallModel) -> AnyElement {
534 let face = control_shell("call-reactions-face", theme::surface_raised())
535 .child(symbol("mood", CONTROL_ICON, theme::text()));
536 if !model.can_react() {
537 return face.opacity(DISABLED_OPACITY).cursor_default().into_any_element();
538 }
539 let app = app.clone();
540 Popover::new("call-reactions-popover")
541 .anchor(Anchor::BottomLeft)
542 .offset(px(10.))
543 .trigger(Button::new("call-reactions").ghost().p_0().size(px(CONTROL_SIZE)).rounded_full().child(face))
544 .content(move |_, _, cx| {
545 let popover = cx.entity().downgrade();
546 h_flex().id("call-reactions-row").gap(px(4.)).children(Reaction::ALL.into_iter().map(|reaction| {
547 let app = app.clone();
548 let popover = popover.clone();
549 div()
550 .id(reaction.name())
551 .size(px(REACTION_CELL))
552 .flex()
553 .items_center()
554 .justify_center()
555 .rounded(px(8.))
556 .text_size(px(24.))
557 .cursor_pointer()
558 .hover(|cell| cell.bg(theme::border_strong()))
559 .child(reaction_glyph(reaction))
560 .on_click(move |_, window, cx| {
561 app.update(cx, |state, cx| state.send_call_reaction(reaction, cx));
562 popover.update(cx, |state, cx| state.dismiss(window, cx)).ok();
563 })
564 }))
565 })
566 .into_any_element()
395 567 }
396 568
397 569 fn leave_menu(app: &Entity<AppState>, model: &CallModel) -> impl IntoElement {
398 570 let leave_app = app.clone();
399 571 let end_app = app.clone();
400 572 let can_end = model.can_end_meeting;
573 let lower_app = app.clone();
574 let can_lower_all = model.can_lower_hands() && model.any_hand_raised();
401 575 Button::new("call-leave-menu")
402 576 .ghost()
403 577 .p_0()
@@ -412,11 +586,20 @@ fn leave_menu(app: &Entity<AppState>, model: &CallModel) -> impl IntoElement {
412 586 .dropdown_menu_with_anchor(Anchor::BottomRight, move |popup, _, _| {
413 587 let leave_app = leave_app.clone();
414 588 let end_app = end_app.clone();
589 let lower_app = lower_app.clone();
415 590 let popup = popup.min_w(px(MENU_WIDTH)).item(
416 591 PopupMenuItem::new("Leave")
417 592 .icon(IconName::PhoneOff)
418 593 .on_click(move |_, _, cx| leave_app.update(cx, |state, cx| state.leave_call(cx))),
419 594 );
595 let popup = if can_lower_all {
596 popup.item(
597 PopupMenuItem::new("Lower all hands")
598 .on_click(move |_, _, cx| lower_app.update(cx, |state, cx| state.lower_all_call_hands(cx))),
599 )
600 } else {
601 popup
602 };
420 603 if can_end {
421 604 popup.item(
422 605 PopupMenuItem::new("End meeting for everyone")
@@ -501,14 +684,37 @@ fn devices_button(app: &Entity<AppState>, model: &CallModel) -> impl IntoElement
501 684 })
502 685 }
503 686
504 fn person_tile(state: &AppState, model: &CallModel, remote: &Tile, size: TileSize, now: Instant) -> AnyElement {
687 fn person_tile(app: &Entity<AppState>, state: &AppState, model: &CallModel, remote: &Tile, size: TileSize, now: Instant) -> AnyElement {
688 let extras = TileExtras {
689 hand: remote.hand.map(|rank| model.hand_position(rank)),
690 reaction: model.chip_of(&remote.mri, now).map(|chip| (chip.reaction, chip.serial)),
691 };
692 let element = person_tile_body(state, model, remote, size, now, &extras);
693 if !(model.can_lower_hands() && remote.hand.is_some()) {
694 return element;
695 }
696 let (app, mri) = (app.clone(), remote.mri.clone());
697 div()
698 .id(SharedString::from(format!("call-tile-{}", remote.mri)))
699 .flex_none()
700 .child(element)
701 .context_menu(move |popup, _, _| {
702 let (app, mri) = (app.clone(), mri.clone());
703 popup.item(PopupMenuItem::new("Lower hand").on_click(move |_, _, cx| {
704 app.update(cx, |state, cx| state.lower_call_hand(mri.clone(), cx));
705 }))
706 })
707 .into_any_element()
708 }
709
710 fn person_tile_body(state: &AppState, model: &CallModel, remote: &Tile, size: TileSize, now: Instant, extras: &TileExtras) -> AnyElement {
505 711 let video = state
506 712 .call
507 713 .as_ref()
508 714 .filter(|_| remote.has_video)
509 715 .and_then(|call| call.pictures.live(&VideoKey::Person(remote.mri.clone()), now));
510 716 if let Some(image) = video {
511 return video_tile(size, image, &remote.name, model.tile_speaking(remote), remote.muted).into_any_element();
717 return video_tile(size, image, &remote.name, model.tile_speaking(remote), remote.muted, extras).into_any_element();
512 718 }
513 719 let waiting = remote.state == TileState::Invited;
514 720 let avatar = person_avatar(&state.directory, remote.user_id.as_deref(), &remote.name, size.avatar);
@@ -517,17 +723,21 @@ fn person_tile(state: &AppState, model: &CallModel, remote: &Tile, size: TileSiz
517 723 let label = div().text_size(px(12.)).text_color(theme::text_muted()).child(text);
518 724 if waiting { pulsing(label, "call-invited-caption") } else { label.into_any_element() }
519 725 });
520 tile(size, avatar, &remote.name, model.tile_speaking(remote), remote.muted, caption).into_any_element()
726 tile(size, avatar, &remote.name, model.tile_speaking(remote), remote.muted, caption, extras).into_any_element()
521 727 }
522 728
523 729 fn own_tile(state: &AppState, model: &CallModel, size: TileSize, now: Instant) -> AnyElement {
730 let extras = TileExtras {
731 hand: model.own_hand.map(|rank| model.hand_position(rank)),
732 reaction: model.own_chip(now).map(|chip| (chip.reaction, chip.serial)),
733 };
524 734 let me = state.directory.me.as_ref();
525 735 let self_view = state
526 736 .call
527 737 .as_ref()
528 738 .and_then(|call| call.pictures.live(&VideoKey::LocalCamera, now));
529 739 if let Some(image) = self_view {
530 return video_tile(size, image, "You", model.local_speaking, model.muted).into_any_element();
740 return video_tile(size, image, "You", model.local_speaking, model.muted, &extras).into_any_element();
531 741 }
532 742 let avatar = person_avatar(
533 743 &state.directory,
@@ -535,15 +745,15 @@ fn own_tile(state: &AppState, model: &CallModel, size: TileSize, now: Instant) -
535 745 me.map_or("You", |person| person.display_name.as_str()),
536 746 size.avatar,
537 747 );
538 tile(size, avatar, "You", model.local_speaking, model.muted, None).into_any_element()
748 tile(size, avatar, "You", model.local_speaking, model.muted, None, &extras).into_any_element()
539 749 }
540 750
541 fn remote_tiles(state: &AppState, model: &CallModel, size: TileSize, hidden_cap: GridLayout, now: Instant) -> Vec<AnyElement> {
751 fn remote_tiles(app: &Entity<AppState>, state: &AppState, model: &CallModel, size: TileSize, hidden_cap: GridLayout, now: Instant) -> Vec<AnyElement> {
542 752 let visible = model.visible_tiles();
543 753 let mut cells: Vec<AnyElement> = visible
544 754 .iter()
545 755 .take(hidden_cap.shown_others)
546 .map(|remote| person_tile(state, model, remote, size, now))
756 .map(|remote| person_tile(app, state, model, remote, size, now))
547 757 .collect();
548 758 if hidden_cap.hidden > 0 {
549 759 cells.push(overflow_tile(size, hidden_cap.hidden).into_any_element());
@@ -551,13 +761,14 @@ fn remote_tiles(state: &AppState, model: &CallModel, size: TileSize, hidden_cap:
551 761 cells
552 762 }
553 763
554 fn people_strip(state: &AppState, model: &CallModel, now: Instant) -> Stateful<Div> {
764 fn people_strip(app: &Entity<AppState>, state: &AppState, model: &CallModel, now: Instant) -> Stateful<Div> {
555 765 let mut cells: Vec<AnyElement> = model
556 766 .strip_tiles()
557 767 .into_iter()
558 .map(|remote| person_tile(state, model, remote, STRIP_TILE, now))
768 .map(|remote| person_tile(app, state, model, remote, STRIP_TILE, now))
559 769 .collect();
560 cells.push(own_tile(state, model, STRIP_TILE, now));
770 let own_index = model.own_cell_index(cells.len());
771 cells.insert(own_index, own_tile(state, model, STRIP_TILE, now));
561 772 v_flex()
562 773 .id("call-strip")
563 774 .flex_none()
@@ -568,7 +779,7 @@ fn people_strip(state: &AppState, model: &CallModel, now: Instant) -> Stateful<D
568 779 .children(cells)
569 780 }
570 781
571 pub fn render_call_view(app: &Entity<AppState>, state: &AppState) -> Option<AnyElement> {
782 pub fn render_call_view(app: &Entity<AppState>, state: &AppState, chat: Option<Entity<ConversationView>>) -> Option<AnyElement> {
572 783 let call = state.call.as_ref()?;
573 784 let model = &call.model;
574 785 let now = Instant::now();
@@ -593,10 +804,13 @@ pub fn render_call_view(app: &Entity<AppState>, state: &AppState) -> Option<AnyE
593 804 )
594 805 .child(div().flex_none().text_size(px(13.)).text_color(status_color).child(status));
595 806
596 let layout = grid_layout(model.visible_tiles().len());
597 let size = tile_size(layout.shown_others + usize::from(layout.hidden > 0) + 1);
598 let mut cells = remote_tiles(state, model, size, layout, now);
599 cells.push(own_tile(state, model, size, now));
807 let max_tiles = if chat.is_some() { CHAT_OPEN_TILES } else { MAX_TILES };
808 let layout = grid_layout(model.visible_tiles().len(), max_tiles);
809 let cells_for_size = if chat.is_some() { MAX_TILES } else { layout.shown_others + usize::from(layout.hidden > 0) + 1 };
810 let size = tile_size(cells_for_size);
811 let mut cells = remote_tiles(app, state, model, size, layout, now);
812 let own_index = model.own_cell_index(cells.len());
813 cells.insert(own_index, own_tile(state, model, size, now));
600 814 let stage = render_stage(app, state, false);
601 815
602 816 let controls = h_flex()
@@ -610,20 +824,21 @@ pub fn render_call_view(app: &Entity<AppState>, state: &AppState) -> Option<AnyE
610 824 .border_color(theme::border())
611 825 .child(mute_button(app, model, "call-mute", CONTROL_SIZE))
612 826 .child(camera_button(app, model))
613 .child(share_button(app, model))
827 .child(share_button(app, model, state.call_share_sound))
828 .child(hand_button(app, model))
829 .child(reactions_button(app, model))
614 830 .child(devices_button(app, model))
615 .when(call.conversation_id.is_some(), |row| row.child(chat_button(app)))
831 .when(call.chat_thread().is_some(), |row| row.child(chat_button(app, call.chat_open, state.call_chat_unread())))
616 832 .child(leave_button(app, model, "call-leave", false))
617 833 .when(model.kind == CallKind::Meeting, |row| row.child(leave_menu(app, model)));
618 834
619 Some(
620 v_flex()
835 let column = v_flex()
621 836 .flex_1()
622 837 .min_w_0()
623 838 .h_full()
624 839 .bg(theme::background())
625 840 .child(header)
626 .children(sharing_banner(app, model))
841 .children(sharing_banner(app, model, state.call_share_sound))
627 842 .child(match stage {
628 843 Some(stage) => h_flex()
629 844 .flex_1()
@@ -632,11 +847,13 @@ pub fn render_call_view(app: &Entity<AppState>, state: &AppState) -> Option<AnyE
632 847 .gap(px(TILE_GAP))
633 848 .items_center()
634 849 .child(stage)
635 .child(people_strip(state, model, now))
850 .child(people_strip(app, state, model, now))
636 851 .into_any_element(),
637 852 None => h_flex()
853 .id("call-grid")
638 854 .flex_1()
639 855 .min_h_0()
856 .overflow_y_scroll()
640 857 .flex_wrap()
641 858 .content_center()
642 859 .p(px(GRID_PADDING))
@@ -646,7 +863,53 @@ pub fn render_call_view(app: &Entity<AppState>, state: &AppState) -> Option<AnyE
646 863 .children(cells)
647 864 .into_any_element(),
648 865 })
649 .child(controls)
866 .child(controls);
867 Some(
868 h_flex()
869 .flex_1()
870 .min_w_0()
871 .h_full()
872 .child(column)
873 .children(chat.map(|chat| chat_panel(app, chat)))
650 874 .into_any_element(),
651 875 )
652 876 }
877
878 fn chat_panel(app: &Entity<AppState>, chat: Entity<ConversationView>) -> AnyElement {
879 let app = app.clone();
880 v_flex()
881 .id("call-chat-panel")
882 .w(px(CHAT_PANEL_WIDTH))
883 .h_full()
884 .flex_none()
885 .border_l_1()
886 .border_color(theme::border())
887 .child(
888 h_flex()
889 .w_full()
890 .h(px(CHAT_HEADER_HEIGHT))
891 .flex_none()
892 .px(px(16.))
893 .items_center()
894 .justify_between()
895 .border_b_1()
896 .border_color(theme::border())
897 .child(div().text_size(px(15.)).font_weight(FontWeight::SEMIBOLD).child("Chat"))
898 .child(
899 div()
900 .id("call-chat-close")
901 .size(px(28.))
902 .flex()
903 .items_center()
904 .justify_center()
905 .rounded_full()
906 .cursor_pointer()
907 .hover(|button| button.bg(theme::row_hover()))
908 .tooltip(|window, cx| Tooltip::new("Close the chat").build(window, cx))
909 .child(icon(IconName::Close, 16., theme::text_muted()))
910 .on_click(move |_, _, cx| app.update(cx, |state, cx| state.toggle_call_chat(cx))),
911 ),
912 )
913 .child(chat)
914 .into_any_element()
915 }
@@ -1,12 +1,14 @@
1use std::sync::Arc;
1use std::sync::Arc;
2use std::time::{Duration, Instant};
2use std::time::{Duration, Instant};
3
3
4use calling::{DeviceEntry, VideoKey};
4use calling::{DeviceEntry, Reaction, VideoKey};
5use gpui_kit::assets::IconName;
5use gpui_kit::assets::IconName;
6use gpui_kit::component::{
6use gpui_kit::component::{
7 button::{Button, ButtonVariants as _},
7 button::{Button, ButtonVariants as _},
8 h_flex,
8 h_flex,
9 menu::{DropdownMenu as _, PopupMenu, PopupMenuItem},
9 menu::{ContextMenuExt as _, DropdownMenu as _, PopupMenu, PopupMenuItem},
10 popover::Popover,
11 switch::Switch,
10 tooltip::Tooltip,
12 tooltip::Tooltip,
11 v_flex,
13 v_flex,
12};
14};
@@ -15,10 +17,13 @@ use gpui_kit::*;
15
17
16use super::avatar::person_avatar;
18use super::avatar::person_avatar;
17use super::call_stage::render_stage;
19use super::call_stage::render_stage;
18use super::widgets::icon;
20use super::conversation::ConversationView;
21use super::widgets::{count_badge, icon, symbol};
19use crate::app_state::AppState;
22use crate::app_state::AppState;
20use crate::call::TileSize;
23use crate::call::TileSize;
21use crate::call::{CallKind, CallModel, GridLayout, Tile, TileState, grid_layout, tile_size};
24use crate::call::{CHAT_OPEN_TILES, CallKind, CallModel, GridLayout, MAX_TILES, Tile, TileState, grid_layout, tile_size};
25use crate::call::REACTION_SHOWN;
26use crate::rows::reaction_glyph as chat_reaction_glyph;
22use crate::theme;
27use crate::theme;
23
28
24const HEADER_HEIGHT: f32 = 60.;
29const HEADER_HEIGHT: f32 = 60.;
@@ -47,6 +52,75 @@ pub const NO_WINDOWS_HINT: &str = "No windows found";
47const BANNER_HEIGHT: f32 = 40.;
52const BANNER_HEIGHT: f32 = 40.;
48const MAX_WINDOW_ITEMS: usize = 12;
53const MAX_WINDOW_ITEMS: usize = 12;
49pub const LOBBY_TEXT: &str = "Waiting in the lobby...";
54pub const LOBBY_TEXT: &str = "Waiting in the lobby...";
55pub const CHAT_PANEL_WIDTH: f32 = 320.;
56const CHAT_HEADER_HEIGHT: f32 = 48.;
57const HAND_GLYPH: &str = "\u{270B}";
58const REACTION_RISE: f32 = 24.;
59const REACTION_FADE_FROM: f32 = 0.75;
60const REACTION_CELL: f32 = 40.;
61const SHARE_SOUND_LABEL: &str = "Include computer sound";
62
63pub fn reaction_glyph(reaction: Reaction) -> String {
64 match reaction {
65 Reaction::Applause => "\u{1F44F}".to_owned(),
66 other => chat_reaction_glyph(other.name()),
67 }
68}
69
70#[derive(Default)]
71struct TileExtras {
72 hand: Option<usize>,
73 reaction: Option<(Reaction, u64)>,
74}
75
76fn hand_badge(position: usize) -> Div {
77 h_flex()
78 .absolute()
79 .top(px(10.))
80 .left(px(10.))
81 .h(px(24.))
82 .px(px(8.))
83 .gap(px(4.))
84 .items_center()
85 .rounded_full()
86 .bg(theme::amber())
87 .text_color(hsla(0., 0., 0.08, 1.))
88 .text_size(px(12.))
89 .font_weight(FontWeight::SEMIBOLD)
90 .child(format!("Hand {position}"))
91}
92
93fn reaction_chip(reaction: Reaction, serial: u64) -> AnyElement {
94 div()
95 .absolute()
96 .right(px(12.))
97 .bottom(px(34.))
98 .size(px(36.))
99 .flex()
100 .items_center()
101 .justify_center()
102 .rounded_full()
103 .bg(theme::surface_raised())
104 .border_1()
105 .border_color(theme::border_strong())
106 .text_size(px(20.))
107 .child(reaction_glyph(reaction))
108 .with_animation(
109 ("call-reaction", serial as usize),
110 Animation::new(REACTION_SHOWN),
111 |chip, delta| {
112 let fade = ((delta - REACTION_FADE_FROM) / (1. - REACTION_FADE_FROM)).clamp(0., 1.);
113 chip.bottom(px(34. + REACTION_RISE * delta)).opacity(1. - fade)
114 },
115 )
116 .into_any_element()
117}
118
119fn tile_overlays(extras: &TileExtras) -> Vec<AnyElement> {
120 let hand = extras.hand.map(|position| hand_badge(position).into_any_element());
121 let reaction = extras.reaction.map(|(reaction, serial)| reaction_chip(reaction, serial));
122 hand.into_iter().chain(reaction).collect()
123}
50
124
51pub fn status_line(model: &CallModel, now: Instant) -> (String, Hsla) {
125pub fn status_line(model: &CallModel, now: Instant) -> (String, Hsla) {
52 if model.lobby {
126 if model.lobby {
@@ -101,7 +175,7 @@ fn mute_badge() -> Div {
101 .child(icon(IconName::MicOff, 13., theme::white()))
175 .child(icon(IconName::MicOff, 13., theme::white()))
102}
176}
103
177
104fn video_tile(size: TileSize, image: Arc<RenderImage>, name: &str, speaking: bool, muted: bool) -> Div {
178fn video_tile(size: TileSize, image: Arc<RenderImage>, name: &str, speaking: bool, muted: bool, extras: &TileExtras) -> Div {
105 div()
179 div()
106 .relative()
180 .relative()
107 .w(px(size.width))
181 .w(px(size.width))
@@ -135,6 +209,7 @@ fn video_tile(size: TileSize, image: Arc<RenderImage>, name: &str, speaking: boo
135 .child(name.to_owned()),
209 .child(name.to_owned()),
136 )
210 )
137 .when(muted, |tile| tile.child(mute_badge()))
211 .when(muted, |tile| tile.child(mute_badge()))
212 .children(tile_overlays(extras))
138}
213}
139
214
140fn tile(
215fn tile(
@@ -144,6 +219,7 @@ fn tile(
144 speaking: bool,
219 speaking: bool,
145 muted: bool,
220 muted: bool,
146 caption: Option<AnyElement>,
221 caption: Option<AnyElement>,
222 extras: &TileExtras,
147) -> Div {
223) -> Div {
148 let badge = div()
224 let badge = div()
149 .absolute()
225 .absolute()
@@ -184,6 +260,7 @@ fn tile(
184 .children(caption),
260 .children(caption),
185 )
261 )
186 .when(muted, |tile| tile.child(badge))
262 .when(muted, |tile| tile.child(badge))
263 .children(tile_overlays(extras))
187}
264}
188
265
189fn overflow_tile(size: TileSize, hidden: usize) -> Div {
266fn overflow_tile(size: TileSize, hidden: usize) -> Div {
@@ -205,7 +282,7 @@ fn overflow_tile(size: TileSize, hidden: usize) -> Div {
205 )
282 )
206}
283}
207
284
208fn round_control(id: &'static str, glyph: IconName, background: Hsla, foreground: Hsla) -> Stateful<Div> {
285fn control_shell(id: &'static str, background: Hsla) -> Stateful<Div> {
209 div()
286 div()
210 .id(id)
287 .id(id)
211 .size(px(CONTROL_SIZE))
288 .size(px(CONTROL_SIZE))
@@ -217,7 +294,10 @@ fn round_control(id: &'static str, glyph: IconName, background: Hsla, foreground
217 .bg(background)
294 .bg(background)
218 .cursor_pointer()
295 .cursor_pointer()
219 .hover(|button| button.opacity(0.85))
296 .hover(|button| button.opacity(0.85))
220 .child(icon(glyph, CONTROL_ICON, foreground))
297}
298
299fn round_control(id: &'static str, glyph: IconName, background: Hsla, foreground: Hsla) -> Stateful<Div> {
300 control_shell(id, background).child(icon(glyph, CONTROL_ICON, foreground))
221}
301}
222
302
223pub fn mute_button(app: &Entity<AppState>, model: &CallModel, id: &'static str, size: f32) -> Stateful<Div> {
303pub fn mute_button(app: &Entity<AppState>, model: &CallModel, id: &'static str, size: f32) -> Stateful<Div> {
@@ -286,10 +366,25 @@ fn camera_button(app: &Entity<AppState>, model: &CallModel) -> Stateful<Div> {
286 })
366 })
287}
367}
288
368
289fn share_items(popup: PopupMenu, app: &Entity<AppState>, model: &CallModel) -> PopupMenu {
369fn sound_switch_item(app: &Entity<AppState>, sound: bool) -> PopupMenuItem {
370 let app = app.clone();
371 PopupMenuItem::element(move |_, _| {
372 h_flex()
373 .id("call-share-sound-row")
374 .w_full()
375 .gap(px(16.))
376 .items_center()
377 .justify_between()
378 .child(SHARE_SOUND_LABEL)
379 .child(Switch::new("call-share-sound").checked(sound))
380 })
381 .on_click(move |_, _, cx| app.update(cx, |state, cx| state.set_call_share_sound(!sound, cx)))
382}
383
384fn share_items(popup: PopupMenu, app: &Entity<AppState>, model: &CallModel, sound: bool) -> PopupMenu {
290 let screens = model.screens();
385 let screens = model.screens();
291 let single_screen = screens.len() == 1;
386 let single_screen = screens.len() == 1;
292 let mut popup = popup.min_w(px(MENU_WIDTH));
387 let mut popup = popup.min_w(px(MENU_WIDTH)).item(sound_switch_item(app, sound)).separator();
293 for (index, source) in screens.into_iter().enumerate() {
388 for (index, source) in screens.into_iter().enumerate() {
294 let label = if single_screen { "Share entire screen".to_owned() } else { format!("Share screen {}", index + 1) };
389 let label = if single_screen { "Share entire screen".to_owned() } else { format!("Share screen {}", index + 1) };
295 let source = source.clone();
390 let source = source.clone();
@@ -318,7 +413,7 @@ fn share_items(popup: PopupMenu, app: &Entity<AppState>, model: &CallModel) -> P
318 popup
413 popup
319}
414}
320
415
321fn share_button(app: &Entity<AppState>, model: &CallModel) -> AnyElement {
416fn share_button(app: &Entity<AppState>, model: &CallModel, sound: bool) -> AnyElement {
322 if model.local_share.is_some() {
417 if model.local_share.is_some() {
323 let app = app.clone();
418 let app = app.clone();
324 return round_control("call-share-stop", IconName::ScreenShareOff, theme::accent(), theme::on_accent())
419 return round_control("call-share-stop", IconName::ScreenShareOff, theme::accent(), theme::on_accent())
@@ -345,12 +440,13 @@ fn share_button(app: &Entity<AppState>, model: &CallModel) -> AnyElement {
345 .size(px(CONTROL_SIZE))
440 .size(px(CONTROL_SIZE))
346 .rounded_full()
441 .rounded_full()
347 .child(face)
442 .child(face)
348 .dropdown_menu_with_anchor(Anchor::BottomLeft, move |popup, _, _| share_items(popup, &app, &model))
443 .dropdown_menu_with_anchor(Anchor::BottomLeft, move |popup, _, _| share_items(popup, &app, &model, sound))
349 .into_any_element()
444 .into_any_element()
350}
445}
351
446
352fn sharing_banner(app: &Entity<AppState>, model: &CallModel) -> Option<AnyElement> {
447fn sharing_banner(app: &Entity<AppState>, model: &CallModel, sound: bool) -> Option<AnyElement> {
353 let label = model.local_share.as_ref()?;
448 let label = model.local_share.as_ref()?;
449 let sound_app = app.clone();
354 let app = app.clone();
450 let app = app.clone();
355 Some(
451 Some(
356 h_flex()
452 h_flex()
@@ -368,6 +464,21 @@ fn sharing_banner(app: &Entity<AppState>, model: &CallModel) -> Option<AnyElemen
368 .font_weight(FontWeight::SEMIBOLD)
464 .font_weight(FontWeight::SEMIBOLD)
369 .child(icon(IconName::ScreenShare, 16., theme::on_accent()))
465 .child(icon(IconName::ScreenShare, 16., theme::on_accent()))
370 .child(format!("You are sharing: {label}"))
466 .child(format!("You are sharing: {label}"))
467 .child(
468 div()
469 .id("call-sharing-sound")
470 .h(px(26.))
471 .px(px(12.))
472 .flex()
473 .items_center()
474 .rounded_full()
475 .border_1()
476 .border_color(theme::on_accent())
477 .cursor_pointer()
478 .hover(|button| button.opacity(0.9))
479 .child(if sound { "Computer sound on" } else { "Computer sound off" })
480 .on_click(move |_, _, cx| sound_app.update(cx, |state, cx| state.set_call_share_sound(!sound, cx))),
481 )
371 .child(
482 .child(
372 div()
483 div()
373 .id("call-sharing-stop")
484 .id("call-sharing-stop")
@@ -387,17 +498,80 @@ fn sharing_banner(app: &Entity<AppState>, model: &CallModel) -> Option<AnyElemen
387 )
498 )
388}
499}
389
500
390fn chat_button(app: &Entity<AppState>) -> Stateful<Div> {
501fn chat_button(app: &Entity<AppState>, open: bool, unread: u32) -> Stateful<Div> {
391 let app = app.clone();
502 let app = app.clone();
392 round_control("call-chat", IconName::MessageCircle, theme::surface_raised(), theme::text())
503 let (background, foreground) = if open {
393 .tooltip(|window, cx| Tooltip::new("Open the chat").build(window, cx))
504 (theme::accent(), theme::on_accent())
394 .on_click(move |_, _, cx| app.update(cx, |state, cx| state.open_call_chat(cx)))
505 } else {
506 (theme::surface_raised(), theme::text())
507 };
508 round_control("call-chat", IconName::MessageCircle, background, foreground)
509 .relative()
510 .tooltip(move |window, cx| Tooltip::new(if open { "Close the chat" } else { "Open the chat" }).build(window, cx))
511 .when(unread > 0, |button| {
512 button.child(div().absolute().top(px(-4.)).right(px(-4.)).child(count_badge(unread, false)))
513 })
514 .on_click(move |_, _, cx| app.update(cx, |state, cx| state.toggle_call_chat(cx)))
515}
516
517fn hand_button(app: &Entity<AppState>, model: &CallModel) -> Stateful<Div> {
518 let raised = model.own_hand.is_some();
519 let background = if raised { theme::accent() } else { theme::surface_raised() };
520 let button = control_shell("call-hand", background).child(div().text_size(px(CONTROL_ICON)).child(HAND_GLYPH));
521 let tooltip = if raised { "Lower hand" } else { "Raise hand" };
522 let button = button.tooltip(move |window, cx| Tooltip::new(tooltip).build(window, cx));
523 if !model.can_react() {
524 return button.opacity(DISABLED_OPACITY).cursor_default();
525 }
526 let app = app.clone();
527 button.on_click(move |_, _, cx| {
528 cx.stop_propagation();
529 app.update(cx, |state, cx| state.toggle_call_hand(cx));
530 })
531}
532
533fn reactions_button(app: &Entity<AppState>, model: &CallModel) -> AnyElement {
534 let face = control_shell("call-reactions-face", theme::surface_raised())
535 .child(symbol("mood", CONTROL_ICON, theme::text()));
536 if !model.can_react() {
537 return face.opacity(DISABLED_OPACITY).cursor_default().into_any_element();
538 }
539 let app = app.clone();
540 Popover::new("call-reactions-popover")
541 .anchor(Anchor::BottomLeft)
542 .offset(px(10.))
543 .trigger(Button::new("call-reactions").ghost().p_0().size(px(CONTROL_SIZE)).rounded_full().child(face))
544 .content(move |_, _, cx| {
545 let popover = cx.entity().downgrade();
546 h_flex().id("call-reactions-row").gap(px(4.)).children(Reaction::ALL.into_iter().map(|reaction| {
547 let app = app.clone();
548 let popover = popover.clone();
549 div()
550 .id(reaction.name())
551 .size(px(REACTION_CELL))
552 .flex()
553 .items_center()
554 .justify_center()
555 .rounded(px(8.))
556 .text_size(px(24.))
557 .cursor_pointer()
558 .hover(|cell| cell.bg(theme::border_strong()))
559 .child(reaction_glyph(reaction))
560 .on_click(move |_, window, cx| {
561 app.update(cx, |state, cx| state.send_call_reaction(reaction, cx));
562 popover.update(cx, |state, cx| state.dismiss(window, cx)).ok();
563 })
564 }))
565 })
566 .into_any_element()
395}
567}
396
568
397fn leave_menu(app: &Entity<AppState>, model: &CallModel) -> impl IntoElement {
569fn leave_menu(app: &Entity<AppState>, model: &CallModel) -> impl IntoElement {
398 let leave_app = app.clone();
570 let leave_app = app.clone();
399 let end_app = app.clone();
571 let end_app = app.clone();
400 let can_end = model.can_end_meeting;
572 let can_end = model.can_end_meeting;
573 let lower_app = app.clone();
574 let can_lower_all = model.can_lower_hands() && model.any_hand_raised();
401 Button::new("call-leave-menu")
575 Button::new("call-leave-menu")
402 .ghost()
576 .ghost()
403 .p_0()
577 .p_0()
@@ -412,11 +586,20 @@ fn leave_menu(app: &Entity<AppState>, model: &CallModel) -> impl IntoElement {
412 .dropdown_menu_with_anchor(Anchor::BottomRight, move |popup, _, _| {
586 .dropdown_menu_with_anchor(Anchor::BottomRight, move |popup, _, _| {
413 let leave_app = leave_app.clone();
587 let leave_app = leave_app.clone();
414 let end_app = end_app.clone();
588 let end_app = end_app.clone();
589 let lower_app = lower_app.clone();
415 let popup = popup.min_w(px(MENU_WIDTH)).item(
590 let popup = popup.min_w(px(MENU_WIDTH)).item(
416 PopupMenuItem::new("Leave")
591 PopupMenuItem::new("Leave")
417 .icon(IconName::PhoneOff)
592 .icon(IconName::PhoneOff)
418 .on_click(move |_, _, cx| leave_app.update(cx, |state, cx| state.leave_call(cx))),
593 .on_click(move |_, _, cx| leave_app.update(cx, |state, cx| state.leave_call(cx))),
419 );
594 );
595 let popup = if can_lower_all {
596 popup.item(
597 PopupMenuItem::new("Lower all hands")
598 .on_click(move |_, _, cx| lower_app.update(cx, |state, cx| state.lower_all_call_hands(cx))),
599 )
600 } else {
601 popup
602 };
420 if can_end {
603 if can_end {
421 popup.item(
604 popup.item(
422 PopupMenuItem::new("End meeting for everyone")
605 PopupMenuItem::new("End meeting for everyone")
@@ -501,14 +684,37 @@ fn devices_button(app: &Entity<AppState>, model: &CallModel) -> impl IntoElement
501 })
684 })
502}
685}
503
686
504fn person_tile(state: &AppState, model: &CallModel, remote: &Tile, size: TileSize, now: Instant) -> AnyElement {
687fn person_tile(app: &Entity<AppState>, state: &AppState, model: &CallModel, remote: &Tile, size: TileSize, now: Instant) -> AnyElement {
688 let extras = TileExtras {
689 hand: remote.hand.map(|rank| model.hand_position(rank)),
690 reaction: model.chip_of(&remote.mri, now).map(|chip| (chip.reaction, chip.serial)),
691 };
692 let element = person_tile_body(state, model, remote, size, now, &extras);
693 if !(model.can_lower_hands() && remote.hand.is_some()) {
694 return element;
695 }
696 let (app, mri) = (app.clone(), remote.mri.clone());
697 div()
698 .id(SharedString::from(format!("call-tile-{}", remote.mri)))
699 .flex_none()
700 .child(element)
701 .context_menu(move |popup, _, _| {
702 let (app, mri) = (app.clone(), mri.clone());
703 popup.item(PopupMenuItem::new("Lower hand").on_click(move |_, _, cx| {
704 app.update(cx, |state, cx| state.lower_call_hand(mri.clone(), cx));
705 }))
706 })
707 .into_any_element()
708}
709
710fn person_tile_body(state: &AppState, model: &CallModel, remote: &Tile, size: TileSize, now: Instant, extras: &TileExtras) -> AnyElement {
505 let video = state
711 let video = state
506 .call
712 .call
507 .as_ref()
713 .as_ref()
508 .filter(|_| remote.has_video)
714 .filter(|_| remote.has_video)
509 .and_then(|call| call.pictures.live(&VideoKey::Person(remote.mri.clone()), now));
715 .and_then(|call| call.pictures.live(&VideoKey::Person(remote.mri.clone()), now));
510 if let Some(image) = video {
716 if let Some(image) = video {
511 return video_tile(size, image, &remote.name, model.tile_speaking(remote), remote.muted).into_any_element();
717 return video_tile(size, image, &remote.name, model.tile_speaking(remote), remote.muted, extras).into_any_element();
512 }
718 }
513 let waiting = remote.state == TileState::Invited;
719 let waiting = remote.state == TileState::Invited;
514 let avatar = person_avatar(&state.directory, remote.user_id.as_deref(), &remote.name, size.avatar);
720 let avatar = person_avatar(&state.directory, remote.user_id.as_deref(), &remote.name, size.avatar);
@@ -517,17 +723,21 @@ fn person_tile(state: &AppState, model: &CallModel, remote: &Tile, size: TileSiz
517 let label = div().text_size(px(12.)).text_color(theme::text_muted()).child(text);
723 let label = div().text_size(px(12.)).text_color(theme::text_muted()).child(text);
518 if waiting { pulsing(label, "call-invited-caption") } else { label.into_any_element() }
724 if waiting { pulsing(label, "call-invited-caption") } else { label.into_any_element() }
519 });
725 });
520 tile(size, avatar, &remote.name, model.tile_speaking(remote), remote.muted, caption).into_any_element()
726 tile(size, avatar, &remote.name, model.tile_speaking(remote), remote.muted, caption, extras).into_any_element()
521}
727}
522
728
523fn own_tile(state: &AppState, model: &CallModel, size: TileSize, now: Instant) -> AnyElement {
729fn own_tile(state: &AppState, model: &CallModel, size: TileSize, now: Instant) -> AnyElement {
730 let extras = TileExtras {
731 hand: model.own_hand.map(|rank| model.hand_position(rank)),
732 reaction: model.own_chip(now).map(|chip| (chip.reaction, chip.serial)),
733 };
524 let me = state.directory.me.as_ref();
734 let me = state.directory.me.as_ref();
525 let self_view = state
735 let self_view = state
526 .call
736 .call
527 .as_ref()
737 .as_ref()
528 .and_then(|call| call.pictures.live(&VideoKey::LocalCamera, now));
738 .and_then(|call| call.pictures.live(&VideoKey::LocalCamera, now));
529 if let Some(image) = self_view {
739 if let Some(image) = self_view {
530 return video_tile(size, image, "You", model.local_speaking, model.muted).into_any_element();
740 return video_tile(size, image, "You", model.local_speaking, model.muted, &extras).into_any_element();
531 }
741 }
532 let avatar = person_avatar(
742 let avatar = person_avatar(
533 &state.directory,
743 &state.directory,
@@ -535,15 +745,15 @@ fn own_tile(state: &AppState, model: &CallModel, size: TileSize, now: Instant) -
535 me.map_or("You", |person| person.display_name.as_str()),
745 me.map_or("You", |person| person.display_name.as_str()),
536 size.avatar,
746 size.avatar,
537 );
747 );
538 tile(size, avatar, "You", model.local_speaking, model.muted, None).into_any_element()
748 tile(size, avatar, "You", model.local_speaking, model.muted, None, &extras).into_any_element()
539}
749}
540
750
541fn remote_tiles(state: &AppState, model: &CallModel, size: TileSize, hidden_cap: GridLayout, now: Instant) -> Vec<AnyElement> {
751fn remote_tiles(app: &Entity<AppState>, state: &AppState, model: &CallModel, size: TileSize, hidden_cap: GridLayout, now: Instant) -> Vec<AnyElement> {
542 let visible = model.visible_tiles();
752 let visible = model.visible_tiles();
543 let mut cells: Vec<AnyElement> = visible
753 let mut cells: Vec<AnyElement> = visible
544 .iter()
754 .iter()
545 .take(hidden_cap.shown_others)
755 .take(hidden_cap.shown_others)
546 .map(|remote| person_tile(state, model, remote, size, now))
756 .map(|remote| person_tile(app, state, model, remote, size, now))
547 .collect();
757 .collect();
548 if hidden_cap.hidden > 0 {
758 if hidden_cap.hidden > 0 {
549 cells.push(overflow_tile(size, hidden_cap.hidden).into_any_element());
759 cells.push(overflow_tile(size, hidden_cap.hidden).into_any_element());
@@ -551,13 +761,14 @@ fn remote_tiles(state: &AppState, model: &CallModel, size: TileSize, hidden_cap:
551 cells
761 cells
552}
762}
553
763
554fn people_strip(state: &AppState, model: &CallModel, now: Instant) -> Stateful<Div> {
764fn people_strip(app: &Entity<AppState>, state: &AppState, model: &CallModel, now: Instant) -> Stateful<Div> {
555 let mut cells: Vec<AnyElement> = model
765 let mut cells: Vec<AnyElement> = model
556 .strip_tiles()
766 .strip_tiles()
557 .into_iter()
767 .into_iter()
558 .map(|remote| person_tile(state, model, remote, STRIP_TILE, now))
768 .map(|remote| person_tile(app, state, model, remote, STRIP_TILE, now))
559 .collect();
769 .collect();
560 cells.push(own_tile(state, model, STRIP_TILE, now));
770 let own_index = model.own_cell_index(cells.len());
771 cells.insert(own_index, own_tile(state, model, STRIP_TILE, now));
561 v_flex()
772 v_flex()
562 .id("call-strip")
773 .id("call-strip")
563 .flex_none()
774 .flex_none()
@@ -568,7 +779,7 @@ fn people_strip(state: &AppState, model: &CallModel, now: Instant) -> Stateful<D
568 .children(cells)
779 .children(cells)
569}
780}
570
781
571pub fn render_call_view(app: &Entity<AppState>, state: &AppState) -> Option<AnyElement> {
782pub fn render_call_view(app: &Entity<AppState>, state: &AppState, chat: Option<Entity<ConversationView>>) -> Option<AnyElement> {
572 let call = state.call.as_ref()?;
783 let call = state.call.as_ref()?;
573 let model = &call.model;
784 let model = &call.model;
574 let now = Instant::now();
785 let now = Instant::now();
@@ -593,10 +804,13 @@ pub fn render_call_view(app: &Entity<AppState>, state: &AppState) -> Option<AnyE
593 )
804 )
594 .child(div().flex_none().text_size(px(13.)).text_color(status_color).child(status));
805 .child(div().flex_none().text_size(px(13.)).text_color(status_color).child(status));
595
806
596 let layout = grid_layout(model.visible_tiles().len());
807 let max_tiles = if chat.is_some() { CHAT_OPEN_TILES } else { MAX_TILES };
597 let size = tile_size(layout.shown_others + usize::from(layout.hidden > 0) + 1);
808 let layout = grid_layout(model.visible_tiles().len(), max_tiles);
598 let mut cells = remote_tiles(state, model, size, layout, now);
809 let cells_for_size = if chat.is_some() { MAX_TILES } else { layout.shown_others + usize::from(layout.hidden > 0) + 1 };
599 cells.push(own_tile(state, model, size, now));
810 let size = tile_size(cells_for_size);
811 let mut cells = remote_tiles(app, state, model, size, layout, now);
812 let own_index = model.own_cell_index(cells.len());
813 cells.insert(own_index, own_tile(state, model, size, now));
600 let stage = render_stage(app, state, false);
814 let stage = render_stage(app, state, false);
601
815
602 let controls = h_flex()
816 let controls = h_flex()
@@ -610,20 +824,21 @@ pub fn render_call_view(app: &Entity<AppState>, state: &AppState) -> Option<AnyE
610 .border_color(theme::border())
824 .border_color(theme::border())
611 .child(mute_button(app, model, "call-mute", CONTROL_SIZE))
825 .child(mute_button(app, model, "call-mute", CONTROL_SIZE))
612 .child(camera_button(app, model))
826 .child(camera_button(app, model))
613 .child(share_button(app, model))
827 .child(share_button(app, model, state.call_share_sound))
828 .child(hand_button(app, model))
829 .child(reactions_button(app, model))
614 .child(devices_button(app, model))
830 .child(devices_button(app, model))
615 .when(call.conversation_id.is_some(), |row| row.child(chat_button(app)))
831 .when(call.chat_thread().is_some(), |row| row.child(chat_button(app, call.chat_open, state.call_chat_unread())))
616 .child(leave_button(app, model, "call-leave", false))
832 .child(leave_button(app, model, "call-leave", false))
617 .when(model.kind == CallKind::Meeting, |row| row.child(leave_menu(app, model)));
833 .when(model.kind == CallKind::Meeting, |row| row.child(leave_menu(app, model)));
618
834
619 Some(
835 let column = v_flex()
620 v_flex()
621 .flex_1()
836 .flex_1()
622 .min_w_0()
837 .min_w_0()
623 .h_full()
838 .h_full()
624 .bg(theme::background())
839 .bg(theme::background())
625 .child(header)
840 .child(header)
626 .children(sharing_banner(app, model))
841 .children(sharing_banner(app, model, state.call_share_sound))
627 .child(match stage {
842 .child(match stage {
628 Some(stage) => h_flex()
843 Some(stage) => h_flex()
629 .flex_1()
844 .flex_1()
@@ -632,11 +847,13 @@ pub fn render_call_view(app: &Entity<AppState>, state: &AppState) -> Option<AnyE
632 .gap(px(TILE_GAP))
847 .gap(px(TILE_GAP))
633 .items_center()
848 .items_center()
634 .child(stage)
849 .child(stage)
635 .child(people_strip(state, model, now))
850 .child(people_strip(app, state, model, now))
636 .into_any_element(),
851 .into_any_element(),
637 None => h_flex()
852 None => h_flex()
853 .id("call-grid")
638 .flex_1()
854 .flex_1()
639 .min_h_0()
855 .min_h_0()
856 .overflow_y_scroll()
640 .flex_wrap()
857 .flex_wrap()
641 .content_center()
858 .content_center()
642 .p(px(GRID_PADDING))
859 .p(px(GRID_PADDING))
@@ -646,7 +863,53 @@ pub fn render_call_view(app: &Entity<AppState>, state: &AppState) -> Option<AnyE
646 .children(cells)
863 .children(cells)
647 .into_any_element(),
864 .into_any_element(),
648 })
865 })
649 .child(controls)
866 .child(controls);
867 Some(
868 h_flex()
869 .flex_1()
870 .min_w_0()
871 .h_full()
872 .child(column)
873 .children(chat.map(|chat| chat_panel(app, chat)))
650 .into_any_element(),
874 .into_any_element(),
651 )
875 )
652}
876}
877
878fn chat_panel(app: &Entity<AppState>, chat: Entity<ConversationView>) -> AnyElement {
879 let app = app.clone();
880 v_flex()
881 .id("call-chat-panel")
882 .w(px(CHAT_PANEL_WIDTH))
883 .h_full()
884 .flex_none()
885 .border_l_1()
886 .border_color(theme::border())
887 .child(
888 h_flex()
889 .w_full()
890 .h(px(CHAT_HEADER_HEIGHT))
891 .flex_none()
892 .px(px(16.))
893 .items_center()
894 .justify_between()
895 .border_b_1()
896 .border_color(theme::border())
897 .child(div().text_size(px(15.)).font_weight(FontWeight::SEMIBOLD).child("Chat"))
898 .child(
899 div()
900 .id("call-chat-close")
901 .size(px(28.))
902 .flex()
903 .items_center()
904 .justify_center()
905 .rounded_full()
906 .cursor_pointer()
907 .hover(|button| button.bg(theme::row_hover()))
908 .tooltip(|window, cx| Tooltip::new("Close the chat").build(window, cx))
909 .child(icon(IconName::Close, 16., theme::text_muted()))
910 .on_click(move |_, _, cx| app.update(cx, |state, cx| state.toggle_call_chat(cx))),
911 ),
912 )
913 .child(chat)
914 .into_any_element()
915}
crates/app/src/views/conversation.rs +18 −3
@@ -142,6 +142,7 @@ struct ReactionDetails {
142 142
143 143 pub struct ConversationView {
144 144 app: Entity<AppState>,
145 pinned: bool,
145 146 scroller: Entity<MessageScrollerState>,
146 147 composer: Entity<Composer>,
147 148 subject: Entity<InputState>,
@@ -388,6 +389,14 @@ impl ConversationView {
388 389 }
389 390
390 391 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
392 Self::build(app, None, window, cx)
393 }
394
395 pub fn pinned_to(app: Entity<AppState>, selection: Selection, window: &mut Window, cx: &mut Context<Self>) -> Self {
396 Self::build(app, Some(selection), window, cx)
397 }
398
399 fn build(app: Entity<AppState>, pinned: Option<Selection>, window: &mut Window, cx: &mut Context<Self>) -> Self {
391 400 let scroller = cx.new(|cx| MessageScrollerState::new(0, cx));
392 401 let composer = cx.new(|cx| Composer::new(app.clone(), window, cx));
393 402 let subject = subject_input(window, cx);
@@ -413,6 +422,7 @@ impl ConversationView {
413 422 ];
414 423 let mut view = ConversationView {
415 424 app,
425 pinned: pinned.is_some(),
416 426 scroller,
417 427 composer,
418 428 subject,
@@ -460,7 +470,7 @@ impl ConversationView {
460 470 new_folder_input: None,
461 471 _subscriptions: subscriptions,
462 472 };
463 if let Some(selection) = view.app.read(cx).selection.clone() {
473 if let Some(selection) = pinned.or_else(|| view.app.read(cx).selection.clone()) {
464 474 view.open(selection, window, cx);
465 475 }
466 476 view
@@ -491,6 +501,7 @@ impl ConversationView {
491 501 cx: &mut Context<Self>,
492 502 ) {
493 503 match event {
504 AppEvent::Selection if self.pinned => {}
494 505 AppEvent::Selection => {
495 506 self.reaction_details = None;
496 507 let (new_chat, selection) = {
@@ -1721,7 +1732,7 @@ impl ConversationView {
1721 1732 return;
1722 1733 }
1723 1734 let state = self.app.read(cx);
1724 if state.viewing_call() {
1735 if state.viewing_call() && !self.pinned {
1725 1736 return;
1726 1737 }
1727 1738 let Some(Selection::Chat(chat_id)) = self.current.as_ref().map(|c| c.selection.clone())
@@ -2971,7 +2982,11 @@ impl ConversationView {
2971 2982 if let Some(note) = channel_note {
2972 2983 subline = note.to_owned();
2973 2984 }
2974 let call_controls = header_call_controls(&self.app, app, &current.selection);
2985 let call_controls = if self.pinned {
2986 Vec::new()
2987 } else {
2988 header_call_controls(&self.app, app, &current.selection)
2989 };
2975 2990 let sync = &current.sync;
2976 2991 if sync.failed {
2977 2992 subline = "Not up to date".to_owned();
@@ -142,6 +142,7 @@ struct ReactionDetails {
142
142
143pub struct ConversationView {
143pub struct ConversationView {
144 app: Entity<AppState>,
144 app: Entity<AppState>,
145 pinned: bool,
145 scroller: Entity<MessageScrollerState>,
146 scroller: Entity<MessageScrollerState>,
146 composer: Entity<Composer>,
147 composer: Entity<Composer>,
147 subject: Entity<InputState>,
148 subject: Entity<InputState>,
@@ -388,6 +389,14 @@ impl ConversationView {
388 }
389 }
389
390
390 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
391 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
392 Self::build(app, None, window, cx)
393 }
394
395 pub fn pinned_to(app: Entity<AppState>, selection: Selection, window: &mut Window, cx: &mut Context<Self>) -> Self {
396 Self::build(app, Some(selection), window, cx)
397 }
398
399 fn build(app: Entity<AppState>, pinned: Option<Selection>, window: &mut Window, cx: &mut Context<Self>) -> Self {
391 let scroller = cx.new(|cx| MessageScrollerState::new(0, cx));
400 let scroller = cx.new(|cx| MessageScrollerState::new(0, cx));
392 let composer = cx.new(|cx| Composer::new(app.clone(), window, cx));
401 let composer = cx.new(|cx| Composer::new(app.clone(), window, cx));
393 let subject = subject_input(window, cx);
402 let subject = subject_input(window, cx);
@@ -413,6 +422,7 @@ impl ConversationView {
413 ];
422 ];
414 let mut view = ConversationView {
423 let mut view = ConversationView {
415 app,
424 app,
425 pinned: pinned.is_some(),
416 scroller,
426 scroller,
417 composer,
427 composer,
418 subject,
428 subject,
@@ -460,7 +470,7 @@ impl ConversationView {
460 new_folder_input: None,
470 new_folder_input: None,
461 _subscriptions: subscriptions,
471 _subscriptions: subscriptions,
462 };
472 };
463 if let Some(selection) = view.app.read(cx).selection.clone() {
473 if let Some(selection) = pinned.or_else(|| view.app.read(cx).selection.clone()) {
464 view.open(selection, window, cx);
474 view.open(selection, window, cx);
465 }
475 }
466 view
476 view
@@ -491,6 +501,7 @@ impl ConversationView {
491 cx: &mut Context<Self>,
501 cx: &mut Context<Self>,
492 ) {
502 ) {
493 match event {
503 match event {
504 AppEvent::Selection if self.pinned => {}
494 AppEvent::Selection => {
505 AppEvent::Selection => {
495 self.reaction_details = None;
506 self.reaction_details = None;
496 let (new_chat, selection) = {
507 let (new_chat, selection) = {
@@ -1721,7 +1732,7 @@ impl ConversationView {
1721 return;
1732 return;
1722 }
1733 }
1723 let state = self.app.read(cx);
1734 let state = self.app.read(cx);
1724 if state.viewing_call() {
1735 if state.viewing_call() && !self.pinned {
1725 return;
1736 return;
1726 }
1737 }
1727 let Some(Selection::Chat(chat_id)) = self.current.as_ref().map(|c| c.selection.clone())
1738 let Some(Selection::Chat(chat_id)) = self.current.as_ref().map(|c| c.selection.clone())
@@ -2971,7 +2982,11 @@ impl ConversationView {
2971 if let Some(note) = channel_note {
2982 if let Some(note) = channel_note {
2972 subline = note.to_owned();
2983 subline = note.to_owned();
2973 }
2984 }
2974 let call_controls = header_call_controls(&self.app, app, &current.selection);
2985 let call_controls = if self.pinned {
2986 Vec::new()
2987 } else {
2988 header_call_controls(&self.app, app, &current.selection)
2989 };
2975 let sync = &current.sync;
2990 let sync = &current.sync;
2976 if sync.failed {
2991 if sync.failed {
2977 subline = "Not up to date".to_owned();
2992 subline = "Not up to date".to_owned();
crates/app/src/views/shell.rs +19 −1
@@ -55,6 +55,7 @@ pub struct AppShell {
55 55 state: Entity<AppState>,
56 56 sidebar: Entity<SidebarView>,
57 57 conversation: Entity<ConversationView>,
58 call_chat: Option<(String, Entity<ConversationView>)>,
58 59 switcher: Option<Entity<Switcher>>,
59 60 notifications: Entity<NotificationCenter>,
60 61 activity: Entity<ActivityCenter>,
@@ -73,6 +74,19 @@ pub struct AppShell {
73 74 }
74 75
75 76 impl AppShell {
77 fn sync_call_chat(&mut self, thread: Option<String>, window: &mut Window, cx: &mut Context<Self>) {
78 match (thread, &self.call_chat) {
79 (Some(wanted), Some((open, _))) if &wanted == open => {}
80 (Some(wanted), _) => {
81 let app = self.state.clone();
82 let selection = Selection::Chat(wanted.clone());
83 let view = cx.new(|cx| ConversationView::pinned_to(app, selection, window, cx));
84 self.call_chat = Some((wanted, view));
85 }
86 (None, _) => self.call_chat = None,
87 }
88 }
89
76 90 pub fn new(
77 91 state: Entity<AppState>,
78 92 open_target: Option<OpenTarget>,
@@ -119,6 +133,7 @@ impl AppShell {
119 133 state,
120 134 sidebar,
121 135 conversation,
136 call_chat: None,
122 137 switcher: None,
123 138 notifications,
124 139 activity,
@@ -513,8 +528,11 @@ impl Render for AppShell {
513 528 state.task_dialog.is_some() || state.status_menu_open
514 529 };
515 530 Overlays::update(cx, |overlays| overlays.panels = panels);
531 let chat_thread = self.state.read(cx).call_chat_thread();
532 self.sync_call_chat(chat_thread, window, cx);
533 let chat_panel = self.call_chat.as_ref().map(|(_, view)| view.clone());
516 534 let state = self.state.read(cx);
517 let call_view = render_call_view(&self.state, state).filter(|_| state.viewing_call());
535 let call_view = render_call_view(&self.state, state, chat_panel).filter(|_| state.viewing_call());
518 536 let call_mini = render_call_mini(&self.state, state);
519 537 let stage_overlay = render_stage_overlay(&self.state, state);
520 538 let status = render_status_bar(
@@ -55,6 +55,7 @@ pub struct AppShell {
55 state: Entity<AppState>,
55 state: Entity<AppState>,
56 sidebar: Entity<SidebarView>,
56 sidebar: Entity<SidebarView>,
57 conversation: Entity<ConversationView>,
57 conversation: Entity<ConversationView>,
58 call_chat: Option<(String, Entity<ConversationView>)>,
58 switcher: Option<Entity<Switcher>>,
59 switcher: Option<Entity<Switcher>>,
59 notifications: Entity<NotificationCenter>,
60 notifications: Entity<NotificationCenter>,
60 activity: Entity<ActivityCenter>,
61 activity: Entity<ActivityCenter>,
@@ -73,6 +74,19 @@ pub struct AppShell {
73}
74}
74
75
75impl AppShell {
76impl AppShell {
77 fn sync_call_chat(&mut self, thread: Option<String>, window: &mut Window, cx: &mut Context<Self>) {
78 match (thread, &self.call_chat) {
79 (Some(wanted), Some((open, _))) if &wanted == open => {}
80 (Some(wanted), _) => {
81 let app = self.state.clone();
82 let selection = Selection::Chat(wanted.clone());
83 let view = cx.new(|cx| ConversationView::pinned_to(app, selection, window, cx));
84 self.call_chat = Some((wanted, view));
85 }
86 (None, _) => self.call_chat = None,
87 }
88 }
89
76 pub fn new(
90 pub fn new(
77 state: Entity<AppState>,
91 state: Entity<AppState>,
78 open_target: Option<OpenTarget>,
92 open_target: Option<OpenTarget>,
@@ -119,6 +133,7 @@ impl AppShell {
119 state,
133 state,
120 sidebar,
134 sidebar,
121 conversation,
135 conversation,
136 call_chat: None,
122 switcher: None,
137 switcher: None,
123 notifications,
138 notifications,
124 activity,
139 activity,
@@ -513,8 +528,11 @@ impl Render for AppShell {
513 state.task_dialog.is_some() || state.status_menu_open
528 state.task_dialog.is_some() || state.status_menu_open
514 };
529 };
515 Overlays::update(cx, |overlays| overlays.panels = panels);
530 Overlays::update(cx, |overlays| overlays.panels = panels);
531 let chat_thread = self.state.read(cx).call_chat_thread();
532 self.sync_call_chat(chat_thread, window, cx);
533 let chat_panel = self.call_chat.as_ref().map(|(_, view)| view.clone());
516 let state = self.state.read(cx);
534 let state = self.state.read(cx);
517 let call_view = render_call_view(&self.state, state).filter(|_| state.viewing_call());
535 let call_view = render_call_view(&self.state, state, chat_panel).filter(|_| state.viewing_call());
518 let call_mini = render_call_mini(&self.state, state);
536 let call_mini = render_call_mini(&self.state, state);
519 let stage_overlay = render_stage_overlay(&self.state, state);
537 let stage_overlay = render_stage_overlay(&self.state, state);
520 let status = render_status_bar(
538 let status = render_status_bar(
crates/calling/Cargo.toml +12 −0
@@ -7,6 +7,7 @@ publish.workspace = true
7 7
8 8 [dependencies]
9 9 base64.workspace = true
10 cpal = "0.17"
10 11 chatsvc.workspace = true
11 12 flate2 = "1"
12 13 futures-util.workspace = true
@@ -19,5 +20,16 @@ thiserror.workspace = true
19 20 tokio.workspace = true
20 21 uuid.workspace = true
21 22
23 [target.'cfg(windows)'.dependencies]
24 windows = { version = "0.62", features = [
25 "Win32_Foundation",
26 "Win32_Media_Audio",
27 "Win32_System_Com",
28 "Win32_System_Com_StructuredStorage",
29 "Win32_System_Threading",
30 "Win32_System_Variant",
31 ] }
32 windows-core = "0.62"
33
22 34 [target.'cfg(windows)'.dev-dependencies]
23 35 webview.workspace = true
@@ -7,6 +7,7 @@ publish.workspace = true
7
7
8[dependencies]
8[dependencies]
9base64.workspace = true
9base64.workspace = true
10cpal = "0.17"
10chatsvc.workspace = true
11chatsvc.workspace = true
11flate2 = "1"
12flate2 = "1"
12futures-util.workspace = true
13futures-util.workspace = true
@@ -19,5 +20,16 @@ thiserror.workspace = true
19tokio.workspace = true
20tokio.workspace = true
20uuid.workspace = true
21uuid.workspace = true
21
22
23[target.'cfg(windows)'.dependencies]
24windows = { version = "0.62", features = [
25 "Win32_Foundation",
26 "Win32_Media_Audio",
27 "Win32_System_Com",
28 "Win32_System_Com_StructuredStorage",
29 "Win32_System_Threading",
30 "Win32_System_Variant",
31] }
32windows-core = "0.62"
33
22[target.'cfg(windows)'.dev-dependencies]
34[target.'cfg(windows)'.dev-dependencies]
23webview.workspace = true
35webview.workspace = true
crates/calling/examples/loopback_probe.rs added +38 −0
@@ -0,0 +1,38 @@
1 use std::time::{Duration, Instant};
2
3 use calling::LoopbackKind;
4 use calling::pcm::SampleQueue;
5 use calling::sound_capture::start_loopback;
6
7 const CAPTURE_TIME: Duration = Duration::from_secs(3);
8 const FRAME_PERIOD: Duration = Duration::from_millis(10);
9
10 fn main() {
11 let queue = SampleQueue::default();
12 let started = match start_loopback(queue.clone()) {
13 Ok(started) => started,
14 Err(error) => {
15 println!("loopback failed to start: {error}");
16 return;
17 }
18 };
19 let mut frames = 0u32;
20 let mut loud_frames = 0u32;
21 let begin = Instant::now();
22 while begin.elapsed() < CAPTURE_TIME {
23 std::thread::sleep(FRAME_PERIOD);
24 let (frame, had_data) = queue.next_frame();
25 if had_data {
26 frames += 1;
27 if frame.iter().any(|&sample| sample != 0) {
28 loud_frames += 1;
29 }
30 }
31 }
32 println!("process exclude mode available: {}", started.kind == LoopbackKind::ProcessExclude);
33 println!("mode: {:?}", started.kind);
34 if let Some(warning) = &started.warning {
35 println!("warning: {warning}");
36 }
37 println!("captured frames (10 ms): {frames}, with non-zero samples: {loud_frames}");
38 }
@@ -0,0 +1,38 @@
1use std::time::{Duration, Instant};
2
3use calling::LoopbackKind;
4use calling::pcm::SampleQueue;
5use calling::sound_capture::start_loopback;
6
7const CAPTURE_TIME: Duration = Duration::from_secs(3);
8const FRAME_PERIOD: Duration = Duration::from_millis(10);
9
10fn main() {
11 let queue = SampleQueue::default();
12 let started = match start_loopback(queue.clone()) {
13 Ok(started) => started,
14 Err(error) => {
15 println!("loopback failed to start: {error}");
16 return;
17 }
18 };
19 let mut frames = 0u32;
20 let mut loud_frames = 0u32;
21 let begin = Instant::now();
22 while begin.elapsed() < CAPTURE_TIME {
23 std::thread::sleep(FRAME_PERIOD);
24 let (frame, had_data) = queue.next_frame();
25 if had_data {
26 frames += 1;
27 if frame.iter().any(|&sample| sample != 0) {
28 loud_frames += 1;
29 }
30 }
31 }
32 println!("process exclude mode available: {}", started.kind == LoopbackKind::ProcessExclude);
33 println!("mode: {:?}", started.kind);
34 if let Some(warning) = &started.warning {
35 println!("warning: {warning}");
36 }
37 println!("captured frames (10 ms): {frames}, with non-zero samples: {loud_frames}");
38}
crates/calling/examples/meet_now.rs +77 −3
@@ -4,7 +4,7 @@ use std::time::{Duration, Instant};
4 4 use calling::meeting::fetch_live_meeting;
5 5 use calling::relay::ic3_scope;
6 6 use calling::signaling::{CHATSVC_REGION, fetch_self};
7 use calling::{CallCommand, CallEngine, CallSpec, CallState, CallUpdate, EngineConfig, MeetingTarget, ShareKind, ShareSource};
7 use calling::{CallCommand, CallEngine, CallSpec, CallState, CallUpdate, EngineConfig, MeetingTarget, Reaction, ShareKind, ShareSource};
8 8 use chatsvc::InstanceNames;
9 9 use serde_json::{Value, json};
10 10 use session::{DEFAULT_ENDPOINT, Method, Request, Scope, Session, SPACES};
@@ -24,6 +24,7 @@ const THREAD_PROPERTY_RETRIES: usize = 8;
24 24 struct Arguments {
25 25 camera: bool,
26 26 share: bool,
27 extras: bool,
27 28 stop_media_after: Option<Duration>,
28 29 hold: Duration,
29 30 thread_out: Option<PathBuf>,
@@ -34,6 +35,7 @@ fn arguments() -> Arguments {
34 35 let mut parsed = Arguments {
35 36 camera: false,
36 37 share: false,
38 extras: false,
37 39 stop_media_after: None,
38 40 hold: Duration::from_secs(10),
39 41 thread_out: None,
@@ -44,6 +46,7 @@ fn arguments() -> Arguments {
44 46 match flag.as_str() {
45 47 "--camera" => parsed.camera = true,
46 48 "--share" => parsed.share = true,
49 "--extras" => parsed.extras = true,
47 50 "--stop-media-after" => parsed.stop_media_after = input.next().and_then(|value| value.parse().ok()).map(Duration::from_secs),
48 51 "--hold" => parsed.hold = Duration::from_secs(input.next().and_then(|value| value.parse().ok()).unwrap_or(10)),
49 52 "--thread-out" => parsed.thread_out = input.next().map(PathBuf::from),
@@ -151,6 +154,11 @@ async fn main() {
151 154 let mut end_sent_at = None;
152 155 let mut media_due: Option<Instant> = None;
153 156 let mut media_stop_due: Option<Instant> = None;
157 let mut hand_lower_due: Option<Instant> = None;
158 let mut hands_seen = 0usize;
159 let mut reactions_seen = Vec::new();
160 let mut sharing_local_level: f32 = 0.0;
161 let mut sharing = false;
154 162 let deadline = Instant::now() + CONNECT_LIMIT + LIVE_STATE_LIMIT + WAIT_FILE_LIMIT + arguments.hold + END_LIMIT;
155 163 let mut tick = tokio::time::interval(POLL);
156 164 while ended.is_none() && Instant::now() < deadline {
@@ -163,10 +171,47 @@ async fn main() {
163 171 }
164 172 }
165 173 Some(CallUpdate::Camera(on)) => println!("# camera update: {on}"),
166 Some(CallUpdate::LocalShare(label)) => println!("# local share update: {}", label.is_some()),
174 Some(CallUpdate::LocalShare(label)) => {
175 sharing = label.is_some();
176 println!("# local share update: {}", label.is_some());
177 }
167 178 Some(CallUpdate::Notice(text)) => println!("# notice: {text}"),
168 179 Some(CallUpdate::State(CallState::Ended { reason })) => ended = Some(reason),
169 Some(CallUpdate::Roster(entries)) => roster_count = Some(entries.len()),
180 Some(CallUpdate::Roster(entries)) => {
181 let hands = entries.iter().filter(|entry| entry.hand.is_some()).count();
182 if hands != hands_seen {
183 println!("# roster hands raised: {hands}");
184 hands_seen = hands;
185 }
186 roster_count = Some(entries.len());
187 }
188 Some(CallUpdate::Reaction { reaction, .. }) => {
189 println!("# reaction received: {reaction:?}");
190 reactions_seen.push(reaction);
191 }
192 Some(CallUpdate::MeetingChat(thread)) => {
193 let url = format!(
194 "https://teams.cloud.microsoft/api/chatsvc/{CHATSVC_REGION}/v1/users/ME/conversations/{}/messages?view=msnp24Equivalent&pageSize=5",
195 urlencoding_component(&thread)
196 );
197 let read = session.request(Method::Get, &url, &ic3_scope(), None).await;
198 match read {
199 Ok(answer) => println!(
200 "# meeting chat thread from join: same as meeting {}, read HTTP {}, messages {}",
201 thread == thread_id,
202 answer.status,
203 answer.body.get("messages").and_then(Value::as_array).map_or(0, Vec::len)
204 ),
205 Err(error) => println!("# meeting chat read failed: {error}"),
206 }
207 }
208 Some(CallUpdate::ShareSound(on)) => println!("# share sound: {on}"),
209 Some(CallUpdate::Muted(muted)) => println!("# muted: {muted}"),
210 Some(CallUpdate::Levels { local, .. }) => {
211 if sharing {
212 sharing_local_level = sharing_local_level.max(local);
213 }
214 }
170 215 Some(CallUpdate::Stats { inbound_packets, .. }) => inbound = inbound_packets,
171 216 Some(_) => {}
172 217 None => break,
@@ -177,12 +222,24 @@ async fn main() {
177 222 let _ = handle.commands.send(CallCommand::SetCamera(false));
178 223 let _ = handle.commands.send(CallCommand::StopShare);
179 224 }
225 if hand_lower_due.is_some_and(|due| Instant::now() >= due) {
226 hand_lower_due = None;
227 let _ = handle.commands.send(CallCommand::SetHand(false));
228 }
180 229 if media_due.is_some_and(|due| Instant::now() >= due) {
181 230 media_due = None;
182 231 media_stop_due = arguments.stop_media_after.map(|after| Instant::now() + after);
183 232 if arguments.camera {
184 233 let _ = handle.commands.send(CallCommand::SetCamera(true));
185 234 }
235 if arguments.extras {
236 let _ = handle.commands.send(CallCommand::SetHand(true));
237 for reaction in Reaction::ALL {
238 let _ = handle.commands.send(CallCommand::SendReaction(reaction));
239 }
240 let _ = handle.commands.send(CallCommand::SetShareSound(true));
241 hand_lower_due = Some(Instant::now() + Duration::from_secs(6));
242 }
186 243 if arguments.share {
187 244 let source = ShareSource { id: 0, kind: ShareKind::Screen, title: String::new() };
188 245 let _ = handle.commands.send(CallCommand::StartShare(source));
@@ -219,6 +276,13 @@ async fn main() {
219 276 "# connected after {connected_after:?}, live state after {live_detected_after:?}, roster {roster_count:?}, inbound packets {inbound}"
220 277 );
221 278 println!("# ended: {ended:?}");
279 if arguments.extras {
280 println!(
281 "# extras: reactions echoed {}/{}, max local level while sharing {sharing_local_level:.3}",
282 reactions_seen.len(),
283 Reaction::ALL.len()
284 );
285 }
222 286 let gone_started = Instant::now();
223 287 let mut gone_after = None;
224 288 while gone_started.elapsed() < GONE_LIMIT {
@@ -232,3 +296,13 @@ async fn main() {
232 296 engine.stop().await;
233 297 println!("# engine stopped, total {:?}", started.elapsed());
234 298 }
299
300 fn urlencoding_component(value: &str) -> String {
301 value
302 .bytes()
303 .map(|byte| match byte {
304 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => (byte as char).to_string(),
305 other => format!("%{other:02X}"),
306 })
307 .collect()
308 }
@@ -4,7 +4,7 @@ use std::time::{Duration, Instant};
4use calling::meeting::fetch_live_meeting;
4use calling::meeting::fetch_live_meeting;
5use calling::relay::ic3_scope;
5use calling::relay::ic3_scope;
6use calling::signaling::{CHATSVC_REGION, fetch_self};
6use calling::signaling::{CHATSVC_REGION, fetch_self};
7use calling::{CallCommand, CallEngine, CallSpec, CallState, CallUpdate, EngineConfig, MeetingTarget, ShareKind, ShareSource};
7use calling::{CallCommand, CallEngine, CallSpec, CallState, CallUpdate, EngineConfig, MeetingTarget, Reaction, ShareKind, ShareSource};
8use chatsvc::InstanceNames;
8use chatsvc::InstanceNames;
9use serde_json::{Value, json};
9use serde_json::{Value, json};
10use session::{DEFAULT_ENDPOINT, Method, Request, Scope, Session, SPACES};
10use session::{DEFAULT_ENDPOINT, Method, Request, Scope, Session, SPACES};
@@ -24,6 +24,7 @@ const THREAD_PROPERTY_RETRIES: usize = 8;
24struct Arguments {
24struct Arguments {
25 camera: bool,
25 camera: bool,
26 share: bool,
26 share: bool,
27 extras: bool,
27 stop_media_after: Option<Duration>,
28 stop_media_after: Option<Duration>,
28 hold: Duration,
29 hold: Duration,
29 thread_out: Option<PathBuf>,
30 thread_out: Option<PathBuf>,
@@ -34,6 +35,7 @@ fn arguments() -> Arguments {
34 let mut parsed = Arguments {
35 let mut parsed = Arguments {
35 camera: false,
36 camera: false,
36 share: false,
37 share: false,
38 extras: false,
37 stop_media_after: None,
39 stop_media_after: None,
38 hold: Duration::from_secs(10),
40 hold: Duration::from_secs(10),
39 thread_out: None,
41 thread_out: None,
@@ -44,6 +46,7 @@ fn arguments() -> Arguments {
44 match flag.as_str() {
46 match flag.as_str() {
45 "--camera" => parsed.camera = true,
47 "--camera" => parsed.camera = true,
46 "--share" => parsed.share = true,
48 "--share" => parsed.share = true,
49 "--extras" => parsed.extras = true,
47 "--stop-media-after" => parsed.stop_media_after = input.next().and_then(|value| value.parse().ok()).map(Duration::from_secs),
50 "--stop-media-after" => parsed.stop_media_after = input.next().and_then(|value| value.parse().ok()).map(Duration::from_secs),
48 "--hold" => parsed.hold = Duration::from_secs(input.next().and_then(|value| value.parse().ok()).unwrap_or(10)),
51 "--hold" => parsed.hold = Duration::from_secs(input.next().and_then(|value| value.parse().ok()).unwrap_or(10)),
49 "--thread-out" => parsed.thread_out = input.next().map(PathBuf::from),
52 "--thread-out" => parsed.thread_out = input.next().map(PathBuf::from),
@@ -151,6 +154,11 @@ async fn main() {
151 let mut end_sent_at = None;
154 let mut end_sent_at = None;
152 let mut media_due: Option<Instant> = None;
155 let mut media_due: Option<Instant> = None;
153 let mut media_stop_due: Option<Instant> = None;
156 let mut media_stop_due: Option<Instant> = None;
157 let mut hand_lower_due: Option<Instant> = None;
158 let mut hands_seen = 0usize;
159 let mut reactions_seen = Vec::new();
160 let mut sharing_local_level: f32 = 0.0;
161 let mut sharing = false;
154 let deadline = Instant::now() + CONNECT_LIMIT + LIVE_STATE_LIMIT + WAIT_FILE_LIMIT + arguments.hold + END_LIMIT;
162 let deadline = Instant::now() + CONNECT_LIMIT + LIVE_STATE_LIMIT + WAIT_FILE_LIMIT + arguments.hold + END_LIMIT;
155 let mut tick = tokio::time::interval(POLL);
163 let mut tick = tokio::time::interval(POLL);
156 while ended.is_none() && Instant::now() < deadline {
164 while ended.is_none() && Instant::now() < deadline {
@@ -163,10 +171,47 @@ async fn main() {
163 }
171 }
164 }
172 }
165 Some(CallUpdate::Camera(on)) => println!("# camera update: {on}"),
173 Some(CallUpdate::Camera(on)) => println!("# camera update: {on}"),
166 Some(CallUpdate::LocalShare(label)) => println!("# local share update: {}", label.is_some()),
174 Some(CallUpdate::LocalShare(label)) => {
175 sharing = label.is_some();
176 println!("# local share update: {}", label.is_some());
177 }
167 Some(CallUpdate::Notice(text)) => println!("# notice: {text}"),
178 Some(CallUpdate::Notice(text)) => println!("# notice: {text}"),
168 Some(CallUpdate::State(CallState::Ended { reason })) => ended = Some(reason),
179 Some(CallUpdate::State(CallState::Ended { reason })) => ended = Some(reason),
169 Some(CallUpdate::Roster(entries)) => roster_count = Some(entries.len()),
180 Some(CallUpdate::Roster(entries)) => {
181 let hands = entries.iter().filter(|entry| entry.hand.is_some()).count();
182 if hands != hands_seen {
183 println!("# roster hands raised: {hands}");
184 hands_seen = hands;
185 }
186 roster_count = Some(entries.len());
187 }
188 Some(CallUpdate::Reaction { reaction, .. }) => {
189 println!("# reaction received: {reaction:?}");
190 reactions_seen.push(reaction);
191 }
192 Some(CallUpdate::MeetingChat(thread)) => {
193 let url = format!(
194 "https://teams.cloud.microsoft/api/chatsvc/{CHATSVC_REGION}/v1/users/ME/conversations/{}/messages?view=msnp24Equivalent&pageSize=5",
195 urlencoding_component(&thread)
196 );
197 let read = session.request(Method::Get, &url, &ic3_scope(), None).await;
198 match read {
199 Ok(answer) => println!(
200 "# meeting chat thread from join: same as meeting {}, read HTTP {}, messages {}",
201 thread == thread_id,
202 answer.status,
203 answer.body.get("messages").and_then(Value::as_array).map_or(0, Vec::len)
204 ),
205 Err(error) => println!("# meeting chat read failed: {error}"),
206 }
207 }
208 Some(CallUpdate::ShareSound(on)) => println!("# share sound: {on}"),
209 Some(CallUpdate::Muted(muted)) => println!("# muted: {muted}"),
210 Some(CallUpdate::Levels { local, .. }) => {
211 if sharing {
212 sharing_local_level = sharing_local_level.max(local);
213 }
214 }
170 Some(CallUpdate::Stats { inbound_packets, .. }) => inbound = inbound_packets,
215 Some(CallUpdate::Stats { inbound_packets, .. }) => inbound = inbound_packets,
171 Some(_) => {}
216 Some(_) => {}
172 None => break,
217 None => break,
@@ -177,12 +222,24 @@ async fn main() {
177 let _ = handle.commands.send(CallCommand::SetCamera(false));
222 let _ = handle.commands.send(CallCommand::SetCamera(false));
178 let _ = handle.commands.send(CallCommand::StopShare);
223 let _ = handle.commands.send(CallCommand::StopShare);
179 }
224 }
225 if hand_lower_due.is_some_and(|due| Instant::now() >= due) {
226 hand_lower_due = None;
227 let _ = handle.commands.send(CallCommand::SetHand(false));
228 }
180 if media_due.is_some_and(|due| Instant::now() >= due) {
229 if media_due.is_some_and(|due| Instant::now() >= due) {
181 media_due = None;
230 media_due = None;
182 media_stop_due = arguments.stop_media_after.map(|after| Instant::now() + after);
231 media_stop_due = arguments.stop_media_after.map(|after| Instant::now() + after);
183 if arguments.camera {
232 if arguments.camera {
184 let _ = handle.commands.send(CallCommand::SetCamera(true));
233 let _ = handle.commands.send(CallCommand::SetCamera(true));
185 }
234 }
235 if arguments.extras {
236 let _ = handle.commands.send(CallCommand::SetHand(true));
237 for reaction in Reaction::ALL {
238 let _ = handle.commands.send(CallCommand::SendReaction(reaction));
239 }
240 let _ = handle.commands.send(CallCommand::SetShareSound(true));
241 hand_lower_due = Some(Instant::now() + Duration::from_secs(6));
242 }
186 if arguments.share {
243 if arguments.share {
187 let source = ShareSource { id: 0, kind: ShareKind::Screen, title: String::new() };
244 let source = ShareSource { id: 0, kind: ShareKind::Screen, title: String::new() };
188 let _ = handle.commands.send(CallCommand::StartShare(source));
245 let _ = handle.commands.send(CallCommand::StartShare(source));
@@ -219,6 +276,13 @@ async fn main() {
219 "# connected after {connected_after:?}, live state after {live_detected_after:?}, roster {roster_count:?}, inbound packets {inbound}"
276 "# connected after {connected_after:?}, live state after {live_detected_after:?}, roster {roster_count:?}, inbound packets {inbound}"
220 );
277 );
221 println!("# ended: {ended:?}");
278 println!("# ended: {ended:?}");
279 if arguments.extras {
280 println!(
281 "# extras: reactions echoed {}/{}, max local level while sharing {sharing_local_level:.3}",
282 reactions_seen.len(),
283 Reaction::ALL.len()
284 );
285 }
222 let gone_started = Instant::now();
286 let gone_started = Instant::now();
223 let mut gone_after = None;
287 let mut gone_after = None;
224 while gone_started.elapsed() < GONE_LIMIT {
288 while gone_started.elapsed() < GONE_LIMIT {
@@ -232,3 +296,13 @@ async fn main() {
232 engine.stop().await;
296 engine.stop().await;
233 println!("# engine stopped, total {:?}", started.elapsed());
297 println!("# engine stopped, total {:?}", started.elapsed());
234}
298}
299
300fn urlencoding_component(value: &str) -> String {
301 value
302 .bytes()
303 .map(|byte| match byte {
304 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => (byte as char).to_string(),
305 other => format!("%{other:02X}"),
306 })
307 .collect()
308}
crates/calling/src/call.rs +153 −4
@@ -25,13 +25,14 @@ use crate::engine::{CallEngine, EngineConfig, Inner};
25 25 use crate::error::{Error, Result};
26 26 use crate::mute::{MuteCommand, MuteEffect};
27 27 use crate::push::CallNotification;
28 use crate::share_audio::ShareAudio;
28 29 use crate::relay::{DEFAULT_RELAY_HOST, RelayGrant, fetch_relay_grant};
29 30 use crate::renegotiation::{MediaAction, MediaNegotiator};
30 31 use crate::roster::Roster;
31 32 use crate::sdp::{RemoteOffer, SignaledOffer, from_teams_offer, stream_lines, to_browser_answer, to_teams_answer, to_teams_offer};
32 33 use crate::signaling::{
33 34 Answer, Attached, Callee, Conversation, Invitation, InviteTarget, LeaveReason, MeetingTarget, Participant, Signaling,
34 TenantRouting, find_echo_bot_thread, escalation_answer_body, renegotiation_body,
35 TenantRouting, chat_thread_id, find_echo_bot_thread, escalation_answer_body, renegotiation_body,
35 36 };
36 37 use crate::state::{CallSignal, CallState};
37 38 use crate::timeline::{Timeline, TimelineEntry};
@@ -628,6 +629,14 @@ async fn drive(
628 629 let echo_thread = thread_id;
629 630 let mut video = VideoReceive::new(own_mri.clone(), VideoRouter::default());
630 631 let mut media_links: BTreeMap<String, String> = BTreeMap::new();
632 let mut share_audio: Option<ShareAudio> = None;
633 let mut share_sound_wanted = false;
634 let mut remote_audio: Option<RtcAudioTrack> = None;
635 let mut own_hand: Option<String> = None;
636 let mut meeting_chat = conversation.chat_thread.clone();
637 if let Some(thread) = &meeting_chat {
638 control.send(CallUpdate::MeetingChat(thread.clone()));
639 }
631 640 loop {
632 641 tokio::select! {
633 642 Some(callback) = callbacks.recv() => {
@@ -761,6 +770,21 @@ async fn drive(
761 770 }
762 771 }
763 772 }
773 Ok(CallEvent::ConversationUpdate(body)) => {
774 replier.reply(request_id, 200, "");
775 if let Some(thread) = chat_thread_id(&body)
776 && meeting_chat.as_ref() != Some(&thread)
777 {
778 control.send(CallUpdate::MeetingChat(thread.clone()));
779 meeting_chat = Some(thread);
780 }
781 }
782 Ok(CallEvent::Reactions(events)) => {
783 replier.reply(request_id, 200, "");
784 for event in events {
785 control.send(CallUpdate::Reaction { mri: event.mri, reaction: event.reaction });
786 }
787 }
764 788 Ok(CallEvent::Progress(status)) => {
765 789 replier.reply(request_id, 200, "");
766 790 if status == ProgressStatus::Ringing {
@@ -824,6 +848,7 @@ async fn drive(
824 848 }
825 849 PeerEvent::Track(remote_track) => {
826 850 timeline.record("remote audio track", "receiving");
851 remote_audio = Some(remote_track.clone());
827 852 if options.record_remote {
828 853 tokio::spawn(record_track(remote_track, recording.clone(), options.tone_hz));
829 854 }
@@ -839,6 +864,11 @@ async fn drive(
839 864 timeline.record("escalation", "new peer connection connected, old one dropped");
840 865 let old = std::mem::replace(&mut current, pending.session);
841 866 old.peer.close();
867 if let Some(audio) = &share_audio
868 && let Err(error) = swap_audio_track(&current.peer, &audio.track)
869 {
870 timeline.record("computer sound not carried over", error.to_string());
871 }
842 872 offered = pending.offered;
843 873 if let Some(media) = &offered
844 874 && let Err(error) = local_video.set_lines(media.video.clone())
@@ -863,7 +893,7 @@ async fn drive(
863 893 },
864 894 command = control.recv() => match command {
865 895 Some(CallCommand::Mute(mute)) => {
866 muted = apply_mute(mute, muted, live.audio.as_ref().expect("audio set above"), &remote, control);
896 muted = apply_mute(mute, muted, live.audio.as_ref().expect("audio set above"), share_audio.as_ref(), &remote, control);
867 897 }
868 898 Some(CallCommand::SelectInput(choice)) => {
869 899 if live.audio.as_ref().is_some_and(AudioSetup::uses_devices) {
@@ -915,6 +945,9 @@ async fn drive(
915 945 Ok(()) => {
916 946 control.send(CallUpdate::LocalShare(Some(source.label())));
917 947 tell_media_descriptions(&remote, &media_links, MediaDescription::share(true), &mut media_description_request, timeline);
948 if share_sound_wanted && share_audio.is_none() {
949 share_audio = engage_share_sound(&factory, options, &input, muted, remote_audio.clone(), &current.peer, control, timeline);
950 }
918 951 }
919 952 Err(error) => control.send(CallUpdate::Notice(format!("Sharing could not start: {error}"))),
920 953 }
@@ -923,11 +956,60 @@ async fn drive(
923 956 Some(CallCommand::StopShare) => {
924 957 if local_video.sharing() {
925 958 local_video.stop_share();
959 release_share_sound(&current.peer, &track, &mut share_audio, control, timeline);
926 960 control.send(CallUpdate::LocalShare(None));
927 961 tell_media_descriptions(&remote, &media_links, MediaDescription::share(false), &mut media_description_request, timeline);
928 962 }
929 963 }
964 Some(CallCommand::SetShareSound(on)) => {
965 share_sound_wanted = on;
966 if local_video.sharing() {
967 if on && share_audio.is_none() {
968 share_audio = engage_share_sound(&factory, options, &input, muted, remote_audio.clone(), &current.peer, control, timeline);
969 } else if !on {
970 release_share_sound(&current.peer, &track, &mut share_audio, control, timeline);
971 }
972 }
973 }
930 974 Some(CallCommand::RefreshShareSources) => refresh_share_sources(control.updates(), options.video),
975 Some(CallCommand::SetHand(true)) => match remote.signaling.raise_hand(&remote.conversation, &remote.participant).await {
976 Ok(state_id) => own_hand = state_id,
977 Err(error) => {
978 timeline.record("raise hand failed", error.to_string());
979 control.send(CallUpdate::Notice("Could not raise your hand".into()));
980 }
981 },
982 Some(CallCommand::SetHand(false)) => {
983 let state_ids: Vec<String> = roster.hand_of(&own_mri).map(|hand| hand.state_id.clone()).or(own_hand.take()).into_iter().collect();
984 own_hand = None;
985 if !state_ids.is_empty()
986 && let Err(error) = remote.signaling.lower_hands(&remote.conversation, &remote.participant, &state_ids).await
987 {
988 timeline.record("lower hand failed", error.to_string());
989 control.send(CallUpdate::Notice("Could not lower your hand".into()));
990 }
991 }
992 Some(CallCommand::LowerHand { mri }) => {
993 let state_ids: Vec<String> = roster.hand_of(&mri).map(|hand| hand.state_id.clone()).into_iter().collect();
994 if !state_ids.is_empty()
995 && let Err(error) = remote.signaling.lower_hands(&remote.conversation, &remote.participant, &state_ids).await
996 {
997 timeline.record("lower hand failed", error.to_string());
998 control.send(CallUpdate::Notice("Could not lower that hand".into()));
999 }
1000 }
1001 Some(CallCommand::LowerAllHands) => {
1002 if let Err(error) = remote.signaling.lower_all_hands(&remote.conversation, &remote.participant).await {
1003 timeline.record("lower all hands failed", error.to_string());
1004 control.send(CallUpdate::Notice("Could not lower all hands".into()));
1005 }
1006 }
1007 Some(CallCommand::SendReaction(reaction)) => {
1008 if let Err(error) = remote.signaling.send_reaction(&remote.conversation, &remote.participant, reaction).await {
1009 timeline.record("reaction failed", error.to_string());
1010 control.send(CallUpdate::Notice("Could not send the reaction".into()));
1011 }
1012 }
931 1013 Some(CallCommand::EndMeeting) => {
932 1014 if is_meeting {
933 1015 match remote.signaling.end_for_all(&remote.conversation, &remote.participant).await {
@@ -949,7 +1031,7 @@ async fn drive(
949 1031 _ = stats_tick.tick(), if remote_set => {
950 1032 let snapshot = collect_stats(&current.peer).await;
951 1033 ticks += 1;
952 let local_level = if muted { 0.0 } else { snapshot.local_level as f32 };
1034 let local_level = if muted && share_audio.is_none() { 0.0 } else { snapshot.local_level as f32 };
953 1035 control.send(CallUpdate::Levels { local: local_level, remote: snapshot.audio_level as f32 });
954 1036 if snapshot.selected_pair.is_some() {
955 1037 report.selected_pair = snapshot.selected_pair.clone();
@@ -1175,9 +1257,19 @@ fn far_future() -> Instant {
1175 1257 Instant::now() + FAR_FUTURE
1176 1258 }
1177 1259
1178 fn apply_mute(command: MuteCommand, currently_muted: bool, audio: &AudioSetup, remote: &RemoteCall, control: &CallControl) -> bool {
1260 fn apply_mute(
1261 command: MuteCommand,
1262 currently_muted: bool,
1263 audio: &AudioSetup,
1264 share_audio: Option<&ShareAudio>,
1265 remote: &RemoteCall,
1266 control: &CallControl,
1267 ) -> bool {
1179 1268 let effect = MuteEffect::for_muted(command.target(currently_muted));
1180 1269 audio.track.set_enabled(effect.track_enabled);
1270 if let Some(share_audio) = share_audio {
1271 share_audio.set_microphone_muted(effect.muted);
1272 }
1181 1273 control.send(CallUpdate::Muted(effect.muted));
1182 1274 let remote = remote.clone();
1183 1275 tokio::spawn(async move {
@@ -1189,6 +1281,63 @@ fn apply_mute(command: MuteCommand, currently_muted: bool, audio: &AudioSetup, r
1189 1281 effect.muted
1190 1282 }
1191 1283
1284 fn swap_audio_track(peer: &PeerConnection, track: &RtcAudioTrack) -> Result<()> {
1285 let sender = peer
1286 .senders()
1287 .into_iter()
1288 .find(|sender| matches!(sender.track(), Some(MediaStreamTrack::Audio(_))))
1289 .ok_or_else(|| Error::Webrtc("no audio sender".into()))?;
1290 sender
1291 .set_track(Some(MediaStreamTrack::Audio(track.clone())))
1292 .map_err(|error| Error::Webrtc(error.to_string()))
1293 }
1294
1295 #[allow(clippy::too_many_arguments)]
1296 fn engage_share_sound(
1297 factory: &PeerConnectionFactory,
1298 options: &CallOptions,
1299 input: &DeviceChoice,
1300 muted: bool,
1301 remote_audio: Option<RtcAudioTrack>,
1302 peer: &PeerConnection,
1303 control: &CallControl,
1304 timeline: &Timeline,
1305 ) -> Option<ShareAudio> {
1306 let started = ShareAudio::start(factory, options.audio, options.tone_hz, input, muted, remote_audio)
1307 .and_then(|audio| swap_audio_track(peer, &audio.track).map(|()| audio));
1308 match started {
1309 Ok(audio) => {
1310 timeline.record("computer sound", format!("{:?}, own playback excluded: {}", audio.loopback, audio.loopback.excludes_own_playback()));
1311 if let Some(warning) = &audio.warning {
1312 timeline.record("computer sound warning", warning.clone());
1313 }
1314 control.send(CallUpdate::ShareSound(true));
1315 Some(audio)
1316 }
1317 Err(error) => {
1318 timeline.record("computer sound failed", error.to_string());
1319 control.send(CallUpdate::Notice("Computer sound could not start, sharing without it".into()));
1320 None
1321 }
1322 }
1323 }
1324
1325 fn release_share_sound(
1326 peer: &PeerConnection,
1327 device_track: &RtcAudioTrack,
1328 share_audio: &mut Option<ShareAudio>,
1329 control: &CallControl,
1330 timeline: &Timeline,
1331 ) {
1332 if share_audio.take().is_none() {
1333 return;
1334 }
1335 if let Err(error) = swap_audio_track(peer, device_track) {
1336 timeline.record("microphone track not restored", error.to_string());
1337 }
1338 control.send(CallUpdate::ShareSound(false));
1339 }
1340
1192 1341 async fn tear_down(mut live: Live, inner: &Inner, timeline: &Timeline, report: &mut CallReport, cancelled: bool) {
1193 1342 if let Some(audio) = &live.audio {
1194 1343 audio.track.set_enabled(false);
@@ -25,13 +25,14 @@ use crate::engine::{CallEngine, EngineConfig, Inner};
25use crate::error::{Error, Result};
25use crate::error::{Error, Result};
26use crate::mute::{MuteCommand, MuteEffect};
26use crate::mute::{MuteCommand, MuteEffect};
27use crate::push::CallNotification;
27use crate::push::CallNotification;
28use crate::share_audio::ShareAudio;
28use crate::relay::{DEFAULT_RELAY_HOST, RelayGrant, fetch_relay_grant};
29use crate::relay::{DEFAULT_RELAY_HOST, RelayGrant, fetch_relay_grant};
29use crate::renegotiation::{MediaAction, MediaNegotiator};
30use crate::renegotiation::{MediaAction, MediaNegotiator};
30use crate::roster::Roster;
31use crate::roster::Roster;
31use crate::sdp::{RemoteOffer, SignaledOffer, from_teams_offer, stream_lines, to_browser_answer, to_teams_answer, to_teams_offer};
32use crate::sdp::{RemoteOffer, SignaledOffer, from_teams_offer, stream_lines, to_browser_answer, to_teams_answer, to_teams_offer};
32use crate::signaling::{
33use crate::signaling::{
33 Answer, Attached, Callee, Conversation, Invitation, InviteTarget, LeaveReason, MeetingTarget, Participant, Signaling,
34 Answer, Attached, Callee, Conversation, Invitation, InviteTarget, LeaveReason, MeetingTarget, Participant, Signaling,
34 TenantRouting, find_echo_bot_thread, escalation_answer_body, renegotiation_body,
35 TenantRouting, chat_thread_id, find_echo_bot_thread, escalation_answer_body, renegotiation_body,
35};
36};
36use crate::state::{CallSignal, CallState};
37use crate::state::{CallSignal, CallState};
37use crate::timeline::{Timeline, TimelineEntry};
38use crate::timeline::{Timeline, TimelineEntry};
@@ -628,6 +629,14 @@ async fn drive(
628 let echo_thread = thread_id;
629 let echo_thread = thread_id;
629 let mut video = VideoReceive::new(own_mri.clone(), VideoRouter::default());
630 let mut video = VideoReceive::new(own_mri.clone(), VideoRouter::default());
630 let mut media_links: BTreeMap<String, String> = BTreeMap::new();
631 let mut media_links: BTreeMap<String, String> = BTreeMap::new();
632 let mut share_audio: Option<ShareAudio> = None;
633 let mut share_sound_wanted = false;
634 let mut remote_audio: Option<RtcAudioTrack> = None;
635 let mut own_hand: Option<String> = None;
636 let mut meeting_chat = conversation.chat_thread.clone();
637 if let Some(thread) = &meeting_chat {
638 control.send(CallUpdate::MeetingChat(thread.clone()));
639 }
631 loop {
640 loop {
632 tokio::select! {
641 tokio::select! {
633 Some(callback) = callbacks.recv() => {
642 Some(callback) = callbacks.recv() => {
@@ -761,6 +770,21 @@ async fn drive(
761 }
770 }
762 }
771 }
763 }
772 }
773 Ok(CallEvent::ConversationUpdate(body)) => {
774 replier.reply(request_id, 200, "");
775 if let Some(thread) = chat_thread_id(&body)
776 && meeting_chat.as_ref() != Some(&thread)
777 {
778 control.send(CallUpdate::MeetingChat(thread.clone()));
779 meeting_chat = Some(thread);
780 }
781 }
782 Ok(CallEvent::Reactions(events)) => {
783 replier.reply(request_id, 200, "");
784 for event in events {
785 control.send(CallUpdate::Reaction { mri: event.mri, reaction: event.reaction });
786 }
787 }
764 Ok(CallEvent::Progress(status)) => {
788 Ok(CallEvent::Progress(status)) => {
765 replier.reply(request_id, 200, "");
789 replier.reply(request_id, 200, "");
766 if status == ProgressStatus::Ringing {
790 if status == ProgressStatus::Ringing {
@@ -824,6 +848,7 @@ async fn drive(
824 }
848 }
825 PeerEvent::Track(remote_track) => {
849 PeerEvent::Track(remote_track) => {
826 timeline.record("remote audio track", "receiving");
850 timeline.record("remote audio track", "receiving");
851 remote_audio = Some(remote_track.clone());
827 if options.record_remote {
852 if options.record_remote {
828 tokio::spawn(record_track(remote_track, recording.clone(), options.tone_hz));
853 tokio::spawn(record_track(remote_track, recording.clone(), options.tone_hz));
829 }
854 }
@@ -839,6 +864,11 @@ async fn drive(
839 timeline.record("escalation", "new peer connection connected, old one dropped");
864 timeline.record("escalation", "new peer connection connected, old one dropped");
840 let old = std::mem::replace(&mut current, pending.session);
865 let old = std::mem::replace(&mut current, pending.session);
841 old.peer.close();
866 old.peer.close();
867 if let Some(audio) = &share_audio
868 && let Err(error) = swap_audio_track(&current.peer, &audio.track)
869 {
870 timeline.record("computer sound not carried over", error.to_string());
871 }
842 offered = pending.offered;
872 offered = pending.offered;
843 if let Some(media) = &offered
873 if let Some(media) = &offered
844 && let Err(error) = local_video.set_lines(media.video.clone())
874 && let Err(error) = local_video.set_lines(media.video.clone())
@@ -863,7 +893,7 @@ async fn drive(
863 },
893 },
864 command = control.recv() => match command {
894 command = control.recv() => match command {
865 Some(CallCommand::Mute(mute)) => {
895 Some(CallCommand::Mute(mute)) => {
866 muted = apply_mute(mute, muted, live.audio.as_ref().expect("audio set above"), &remote, control);
896 muted = apply_mute(mute, muted, live.audio.as_ref().expect("audio set above"), share_audio.as_ref(), &remote, control);
867 }
897 }
868 Some(CallCommand::SelectInput(choice)) => {
898 Some(CallCommand::SelectInput(choice)) => {
869 if live.audio.as_ref().is_some_and(AudioSetup::uses_devices) {
899 if live.audio.as_ref().is_some_and(AudioSetup::uses_devices) {
@@ -915,6 +945,9 @@ async fn drive(
915 Ok(()) => {
945 Ok(()) => {
916 control.send(CallUpdate::LocalShare(Some(source.label())));
946 control.send(CallUpdate::LocalShare(Some(source.label())));
917 tell_media_descriptions(&remote, &media_links, MediaDescription::share(true), &mut media_description_request, timeline);
947 tell_media_descriptions(&remote, &media_links, MediaDescription::share(true), &mut media_description_request, timeline);
948 if share_sound_wanted && share_audio.is_none() {
949 share_audio = engage_share_sound(&factory, options, &input, muted, remote_audio.clone(), &current.peer, control, timeline);
950 }
918 }
951 }
919 Err(error) => control.send(CallUpdate::Notice(format!("Sharing could not start: {error}"))),
952 Err(error) => control.send(CallUpdate::Notice(format!("Sharing could not start: {error}"))),
920 }
953 }
@@ -923,11 +956,60 @@ async fn drive(
923 Some(CallCommand::StopShare) => {
956 Some(CallCommand::StopShare) => {
924 if local_video.sharing() {
957 if local_video.sharing() {
925 local_video.stop_share();
958 local_video.stop_share();
959 release_share_sound(&current.peer, &track, &mut share_audio, control, timeline);
926 control.send(CallUpdate::LocalShare(None));
960 control.send(CallUpdate::LocalShare(None));
927 tell_media_descriptions(&remote, &media_links, MediaDescription::share(false), &mut media_description_request, timeline);
961 tell_media_descriptions(&remote, &media_links, MediaDescription::share(false), &mut media_description_request, timeline);
928 }
962 }
929 }
963 }
964 Some(CallCommand::SetShareSound(on)) => {
965 share_sound_wanted = on;
966 if local_video.sharing() {
967 if on && share_audio.is_none() {
968 share_audio = engage_share_sound(&factory, options, &input, muted, remote_audio.clone(), &current.peer, control, timeline);
969 } else if !on {
970 release_share_sound(&current.peer, &track, &mut share_audio, control, timeline);
971 }
972 }
973 }
930 Some(CallCommand::RefreshShareSources) => refresh_share_sources(control.updates(), options.video),
974 Some(CallCommand::RefreshShareSources) => refresh_share_sources(control.updates(), options.video),
975 Some(CallCommand::SetHand(true)) => match remote.signaling.raise_hand(&remote.conversation, &remote.participant).await {
976 Ok(state_id) => own_hand = state_id,
977 Err(error) => {
978 timeline.record("raise hand failed", error.to_string());
979 control.send(CallUpdate::Notice("Could not raise your hand".into()));
980 }
981 },
982 Some(CallCommand::SetHand(false)) => {
983 let state_ids: Vec<String> = roster.hand_of(&own_mri).map(|hand| hand.state_id.clone()).or(own_hand.take()).into_iter().collect();
984 own_hand = None;
985 if !state_ids.is_empty()
986 && let Err(error) = remote.signaling.lower_hands(&remote.conversation, &remote.participant, &state_ids).await
987 {
988 timeline.record("lower hand failed", error.to_string());
989 control.send(CallUpdate::Notice("Could not lower your hand".into()));
990 }
991 }
992 Some(CallCommand::LowerHand { mri }) => {
993 let state_ids: Vec<String> = roster.hand_of(&mri).map(|hand| hand.state_id.clone()).into_iter().collect();
994 if !state_ids.is_empty()
995 && let Err(error) = remote.signaling.lower_hands(&remote.conversation, &remote.participant, &state_ids).await
996 {
997 timeline.record("lower hand failed", error.to_string());
998 control.send(CallUpdate::Notice("Could not lower that hand".into()));
999 }
1000 }
1001 Some(CallCommand::LowerAllHands) => {
1002 if let Err(error) = remote.signaling.lower_all_hands(&remote.conversation, &remote.participant).await {
1003 timeline.record("lower all hands failed", error.to_string());
1004 control.send(CallUpdate::Notice("Could not lower all hands".into()));
1005 }
1006 }
1007 Some(CallCommand::SendReaction(reaction)) => {
1008 if let Err(error) = remote.signaling.send_reaction(&remote.conversation, &remote.participant, reaction).await {
1009 timeline.record("reaction failed", error.to_string());
1010 control.send(CallUpdate::Notice("Could not send the reaction".into()));
1011 }
1012 }
931 Some(CallCommand::EndMeeting) => {
1013 Some(CallCommand::EndMeeting) => {
932 if is_meeting {
1014 if is_meeting {
933 match remote.signaling.end_for_all(&remote.conversation, &remote.participant).await {
1015 match remote.signaling.end_for_all(&remote.conversation, &remote.participant).await {
@@ -949,7 +1031,7 @@ async fn drive(
949 _ = stats_tick.tick(), if remote_set => {
1031 _ = stats_tick.tick(), if remote_set => {
950 let snapshot = collect_stats(&current.peer).await;
1032 let snapshot = collect_stats(&current.peer).await;
951 ticks += 1;
1033 ticks += 1;
952 let local_level = if muted { 0.0 } else { snapshot.local_level as f32 };
1034 let local_level = if muted && share_audio.is_none() { 0.0 } else { snapshot.local_level as f32 };
953 control.send(CallUpdate::Levels { local: local_level, remote: snapshot.audio_level as f32 });
1035 control.send(CallUpdate::Levels { local: local_level, remote: snapshot.audio_level as f32 });
954 if snapshot.selected_pair.is_some() {
1036 if snapshot.selected_pair.is_some() {
955 report.selected_pair = snapshot.selected_pair.clone();
1037 report.selected_pair = snapshot.selected_pair.clone();
@@ -1175,9 +1257,19 @@ fn far_future() -> Instant {
1175 Instant::now() + FAR_FUTURE
1257 Instant::now() + FAR_FUTURE
1176}
1258}
1177
1259
1178fn apply_mute(command: MuteCommand, currently_muted: bool, audio: &AudioSetup, remote: &RemoteCall, control: &CallControl) -> bool {
1260fn apply_mute(
1261 command: MuteCommand,
1262 currently_muted: bool,
1263 audio: &AudioSetup,
1264 share_audio: Option<&ShareAudio>,
1265 remote: &RemoteCall,
1266 control: &CallControl,
1267) -> bool {
1179 let effect = MuteEffect::for_muted(command.target(currently_muted));
1268 let effect = MuteEffect::for_muted(command.target(currently_muted));
1180 audio.track.set_enabled(effect.track_enabled);
1269 audio.track.set_enabled(effect.track_enabled);
1270 if let Some(share_audio) = share_audio {
1271 share_audio.set_microphone_muted(effect.muted);
1272 }
1181 control.send(CallUpdate::Muted(effect.muted));
1273 control.send(CallUpdate::Muted(effect.muted));
1182 let remote = remote.clone();
1274 let remote = remote.clone();
1183 tokio::spawn(async move {
1275 tokio::spawn(async move {
@@ -1189,6 +1281,63 @@ fn apply_mute(command: MuteCommand, currently_muted: bool, audio: &AudioSetup, r
1189 effect.muted
1281 effect.muted
1190}
1282}
1191
1283
1284fn swap_audio_track(peer: &PeerConnection, track: &RtcAudioTrack) -> Result<()> {
1285 let sender = peer
1286 .senders()
1287 .into_iter()
1288 .find(|sender| matches!(sender.track(), Some(MediaStreamTrack::Audio(_))))
1289 .ok_or_else(|| Error::Webrtc("no audio sender".into()))?;
1290 sender
1291 .set_track(Some(MediaStreamTrack::Audio(track.clone())))
1292 .map_err(|error| Error::Webrtc(error.to_string()))
1293}
1294
1295#[allow(clippy::too_many_arguments)]
1296fn engage_share_sound(
1297 factory: &PeerConnectionFactory,
1298 options: &CallOptions,
1299 input: &DeviceChoice,
1300 muted: bool,
1301 remote_audio: Option<RtcAudioTrack>,
1302 peer: &PeerConnection,
1303 control: &CallControl,
1304 timeline: &Timeline,
1305) -> Option<ShareAudio> {
1306 let started = ShareAudio::start(factory, options.audio, options.tone_hz, input, muted, remote_audio)
1307 .and_then(|audio| swap_audio_track(peer, &audio.track).map(|()| audio));
1308 match started {
1309 Ok(audio) => {
1310 timeline.record("computer sound", format!("{:?}, own playback excluded: {}", audio.loopback, audio.loopback.excludes_own_playback()));
1311 if let Some(warning) = &audio.warning {
1312 timeline.record("computer sound warning", warning.clone());
1313 }
1314 control.send(CallUpdate::ShareSound(true));
1315 Some(audio)
1316 }
1317 Err(error) => {
1318 timeline.record("computer sound failed", error.to_string());
1319 control.send(CallUpdate::Notice("Computer sound could not start, sharing without it".into()));
1320 None
1321 }
1322 }
1323}
1324
1325fn release_share_sound(
1326 peer: &PeerConnection,
1327 device_track: &RtcAudioTrack,
1328 share_audio: &mut Option<ShareAudio>,
1329 control: &CallControl,
1330 timeline: &Timeline,
1331) {
1332 if share_audio.take().is_none() {
1333 return;
1334 }
1335 if let Err(error) = swap_audio_track(peer, device_track) {
1336 timeline.record("microphone track not restored", error.to_string());
1337 }
1338 control.send(CallUpdate::ShareSound(false));
1339}
1340
1192async fn tear_down(mut live: Live, inner: &Inner, timeline: &Timeline, report: &mut CallReport, cancelled: bool) {
1341async fn tear_down(mut live: Live, inner: &Inner, timeline: &Timeline, report: &mut CallReport, cancelled: bool) {
1193 if let Some(audio) = &live.audio {
1342 if let Some(audio) = &live.audio {
1194 audio.track.set_enabled(false);
1343 audio.track.set_enabled(false);
crates/calling/src/control.rs +16 −0
@@ -6,6 +6,7 @@ use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel};
6 6 use crate::devices::{DeviceChoice, DeviceLists};
7 7 use crate::error::{Error, Result};
8 8 use crate::mute::MuteCommand;
9 use crate::reaction::Reaction;
9 10 use crate::roster::RosterEntry;
10 11 use crate::camera::CameraDevice;
11 12 use crate::screen::ShareSource;
@@ -22,7 +23,12 @@ pub enum CallCommand {
22 23 SelectCamera(DeviceChoice),
23 24 StartShare(ShareSource),
24 25 StopShare,
26 SetShareSound(bool),
25 27 RefreshShareSources,
28 SetHand(bool),
29 LowerHand { mri: String },
30 LowerAllHands,
31 SendReaction(Reaction),
26 32 Hangup,
27 33 EndMeeting,
28 34 }
@@ -53,6 +59,9 @@ pub enum CallUpdate {
53 59 Cameras(Vec<CameraDevice>),
54 60 LocalShare(Option<String>),
55 61 ShareSources(Vec<ShareSource>),
62 ShareSound(bool),
63 Reaction { mri: String, reaction: Reaction },
64 MeetingChat(String),
56 65 Notice(String),
57 66 }
58 67
@@ -97,6 +106,13 @@ impl CallControl {
97 106 self.updates.clone()
98 107 }
99 108
109 pub fn try_recv_command(&mut self) -> Option<CallCommand> {
110 if !self.deferred.is_empty() {
111 return Some(self.deferred.remove(0));
112 }
113 self.commands.try_recv().ok()
114 }
115
100 116 pub async fn recv(&mut self) -> Option<CallCommand> {
101 117 if !self.deferred.is_empty() {
102 118 return Some(self.deferred.remove(0));
@@ -6,6 +6,7 @@ use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel};
6use crate::devices::{DeviceChoice, DeviceLists};
6use crate::devices::{DeviceChoice, DeviceLists};
7use crate::error::{Error, Result};
7use crate::error::{Error, Result};
8use crate::mute::MuteCommand;
8use crate::mute::MuteCommand;
9use crate::reaction::Reaction;
9use crate::roster::RosterEntry;
10use crate::roster::RosterEntry;
10use crate::camera::CameraDevice;
11use crate::camera::CameraDevice;
11use crate::screen::ShareSource;
12use crate::screen::ShareSource;
@@ -22,7 +23,12 @@ pub enum CallCommand {
22 SelectCamera(DeviceChoice),
23 SelectCamera(DeviceChoice),
23 StartShare(ShareSource),
24 StartShare(ShareSource),
24 StopShare,
25 StopShare,
26 SetShareSound(bool),
25 RefreshShareSources,
27 RefreshShareSources,
28 SetHand(bool),
29 LowerHand { mri: String },
30 LowerAllHands,
31 SendReaction(Reaction),
26 Hangup,
32 Hangup,
27 EndMeeting,
33 EndMeeting,
28}
34}
@@ -53,6 +59,9 @@ pub enum CallUpdate {
53 Cameras(Vec<CameraDevice>),
59 Cameras(Vec<CameraDevice>),
54 LocalShare(Option<String>),
60 LocalShare(Option<String>),
55 ShareSources(Vec<ShareSource>),
61 ShareSources(Vec<ShareSource>),
62 ShareSound(bool),
63 Reaction { mri: String, reaction: Reaction },
64 MeetingChat(String),
56 Notice(String),
65 Notice(String),
57}
66}
58
67
@@ -97,6 +106,13 @@ impl CallControl {
97 self.updates.clone()
106 self.updates.clone()
98 }
107 }
99
108
109 pub fn try_recv_command(&mut self) -> Option<CallCommand> {
110 if !self.deferred.is_empty() {
111 return Some(self.deferred.remove(0));
112 }
113 self.commands.try_recv().ok()
114 }
115
100 pub async fn recv(&mut self) -> Option<CallCommand> {
116 pub async fn recv(&mut self) -> Option<CallCommand> {
101 if !self.deferred.is_empty() {
117 if !self.deferred.is_empty() {
102 return Some(self.deferred.remove(0));
118 return Some(self.deferred.remove(0));
crates/calling/src/error.rs +2 −0
@@ -8,6 +8,8 @@ pub enum Error {
8 8 Callback(String),
9 9 #[error("webrtc: {0}")]
10 10 Webrtc(String),
11 #[error("audio: {0}")]
12 Audio(String),
11 13 #[error("call cancelled")]
12 14 Cancelled,
13 15 #[error(transparent)]
@@ -8,6 +8,8 @@ pub enum Error {
8 Callback(String),
8 Callback(String),
9 #[error("webrtc: {0}")]
9 #[error("webrtc: {0}")]
10 Webrtc(String),
10 Webrtc(String),
11 #[error("audio: {0}")]
12 Audio(String),
11 #[error("call cancelled")]
13 #[error("call cancelled")]
12 Cancelled,
14 Cancelled,
13 #[error(transparent)]
15 #[error(transparent)]
crates/calling/src/lib.rs +10 −1
@@ -9,16 +9,23 @@ pub mod engine;
9 9 pub mod end;
10 10 pub mod error;
11 11 pub mod level;
12 #[cfg(windows)]
13 mod loopback_windows;
12 14 pub mod meeting;
15 pub mod mixer;
13 16 pub mod mute;
17 pub mod pcm;
14 18 pub mod push;
19 pub mod reaction;
15 20 pub mod relay;
16 21 pub mod renegotiation;
17 22 pub mod ring;
18 23 pub mod roster;
19 24 pub mod screen;
20 25 pub mod sdp;
26 pub mod share_audio;
21 27 pub mod signaling;
28 pub mod sound_capture;
22 29 pub mod state;
23 30 pub mod timeline;
24 31 pub mod trouter_events;
@@ -35,7 +42,9 @@ pub use end::EndKind;
35 42 pub use engine::{CallEngine, EngineConfig, EngineEvent, IncomingRing};
36 43 pub use push::Caller;
37 44 pub use ring::{RING_TIMEOUT, RingEnd, RingSignal, RingState};
38 pub use roster::RosterEntry;
45 pub use reaction::{Reaction, ReactionEvent};
46 pub use roster::{RaisedHand, RosterEntry};
47 pub use sound_capture::LoopbackKind;
39 48 pub use signaling::{Callee, MeetingTarget};
40 49 pub use devices::{AudioDevice, DeviceChoice, DeviceEntry, DeviceLists};
41 50 pub use error::{Error, Result};
@@ -9,16 +9,23 @@ pub mod engine;
9pub mod end;
9pub mod end;
10pub mod error;
10pub mod error;
11pub mod level;
11pub mod level;
12#[cfg(windows)]
13mod loopback_windows;
12pub mod meeting;
14pub mod meeting;
15pub mod mixer;
13pub mod mute;
16pub mod mute;
17pub mod pcm;
14pub mod push;
18pub mod push;
19pub mod reaction;
15pub mod relay;
20pub mod relay;
16pub mod renegotiation;
21pub mod renegotiation;
17pub mod ring;
22pub mod ring;
18pub mod roster;
23pub mod roster;
19pub mod screen;
24pub mod screen;
20pub mod sdp;
25pub mod sdp;
26pub mod share_audio;
21pub mod signaling;
27pub mod signaling;
28pub mod sound_capture;
22pub mod state;
29pub mod state;
23pub mod timeline;
30pub mod timeline;
24pub mod trouter_events;
31pub mod trouter_events;
@@ -35,7 +42,9 @@ pub use end::EndKind;
35pub use engine::{CallEngine, EngineConfig, EngineEvent, IncomingRing};
42pub use engine::{CallEngine, EngineConfig, EngineEvent, IncomingRing};
36pub use push::Caller;
43pub use push::Caller;
37pub use ring::{RING_TIMEOUT, RingEnd, RingSignal, RingState};
44pub use ring::{RING_TIMEOUT, RingEnd, RingSignal, RingState};
38pub use roster::RosterEntry;
45pub use reaction::{Reaction, ReactionEvent};
46pub use roster::{RaisedHand, RosterEntry};
47pub use sound_capture::LoopbackKind;
39pub use signaling::{Callee, MeetingTarget};
48pub use signaling::{Callee, MeetingTarget};
40pub use devices::{AudioDevice, DeviceChoice, DeviceEntry, DeviceLists};
49pub use devices::{AudioDevice, DeviceChoice, DeviceEntry, DeviceLists};
41pub use error::{Error, Result};
50pub use error::{Error, Result};
crates/calling/src/loopback_windows.rs added +172 −0
@@ -0,0 +1,172 @@
1 use std::mem::{ManuallyDrop, size_of};
2 use std::sync::mpsc;
3 use std::time::Duration;
4
5 use windows::Win32::Foundation::{CloseHandle, E_FAIL, HANDLE, WAIT_OBJECT_0};
6 use windows::Win32::Media::Audio::{
7 AUDCLNT_BUFFERFLAGS_SILENT, AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM, AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
8 AUDCLNT_STREAMFLAGS_LOOPBACK, AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY, AUDIOCLIENT_ACTIVATION_PARAMS,
9 AUDIOCLIENT_ACTIVATION_PARAMS_0, AUDIOCLIENT_ACTIVATION_TYPE_PROCESS_LOOPBACK, AUDIOCLIENT_PROCESS_LOOPBACK_PARAMS,
10 ActivateAudioInterfaceAsync, IActivateAudioInterfaceAsyncOperation, IActivateAudioInterfaceCompletionHandler,
11 IActivateAudioInterfaceCompletionHandler_Impl, IAudioCaptureClient, IAudioClient, PROCESS_LOOPBACK_MODE_EXCLUDE_TARGET_PROCESS_TREE,
12 VIRTUAL_AUDIO_DEVICE_PROCESS_LOOPBACK, WAVEFORMATEX,
13 };
14 use windows::Win32::System::Com::StructuredStorage::PROPVARIANT;
15 use windows::Win32::System::Com::{BLOB, COINIT_MULTITHREADED, CoInitializeEx, CoUninitialize, IAgileObject, IAgileObject_Impl};
16 use windows::Win32::System::Threading::{CreateEventW, WaitForSingleObject};
17 use windows::Win32::System::Variant::VT_BLOB;
18 use windows::core::{Interface, Ref};
19 use windows_core::implement;
20
21 use crate::audio::SAMPLE_RATE;
22 use crate::capture::Capture;
23 use crate::error::{Error, Result};
24 use crate::pcm::SampleQueue;
25
26 const CHANNELS: u16 = 2;
27 const BITS: u16 = 16;
28 const ACTIVATION_WAIT: Duration = Duration::from_secs(5);
29 const EVENT_WAIT_MS: u32 = 100;
30 const PCM_TAG: u16 = 1;
31
32 struct ActivatedClient(IAudioClient);
33
34 unsafe impl Send for ActivatedClient {}
35
36 #[implement(IActivateAudioInterfaceCompletionHandler, IAgileObject)]
37 struct ActivationHandler {
38 sender: mpsc::Sender<windows::core::Result<ActivatedClient>>,
39 }
40
41 impl IAgileObject_Impl for ActivationHandler_Impl {}
42
43 impl IActivateAudioInterfaceCompletionHandler_Impl for ActivationHandler_Impl {
44 fn ActivateCompleted(&self, operation: Ref<IActivateAudioInterfaceAsyncOperation>) -> windows::core::Result<()> {
45 let activated = (|| unsafe {
46 let operation = operation.ok()?;
47 let mut result = windows::core::HRESULT(0);
48 let mut unknown = None;
49 operation.GetActivateResult(&mut result, &mut unknown)?;
50 result.ok()?;
51 let unknown: windows::core::IUnknown = unknown.ok_or_else(|| windows::core::Error::from(E_FAIL))?;
52 unknown.cast::<IAudioClient>().map(ActivatedClient)
53 })();
54 let _ = self.sender.send(activated);
55 Ok(())
56 }
57 }
58
59 fn audio_error(what: &str, error: impl std::fmt::Display) -> Error {
60 Error::Audio(format!("{what}: {error}"))
61 }
62
63 fn activate_excluding(process_id: u32) -> Result<IAudioClient> {
64 let mut parameters = AUDIOCLIENT_ACTIVATION_PARAMS {
65 ActivationType: AUDIOCLIENT_ACTIVATION_TYPE_PROCESS_LOOPBACK,
66 Anonymous: AUDIOCLIENT_ACTIVATION_PARAMS_0 {
67 ProcessLoopbackParams: AUDIOCLIENT_PROCESS_LOOPBACK_PARAMS {
68 TargetProcessId: process_id,
69 ProcessLoopbackMode: PROCESS_LOOPBACK_MODE_EXCLUDE_TARGET_PROCESS_TREE,
70 },
71 },
72 };
73 let mut variant = ManuallyDrop::new(PROPVARIANT::default());
74 unsafe {
75 let inner = &mut *variant.Anonymous.Anonymous;
76 inner.vt = VT_BLOB;
77 inner.Anonymous.blob = BLOB {
78 cbSize: size_of::<AUDIOCLIENT_ACTIVATION_PARAMS>() as u32,
79 pBlobData: (&raw mut parameters).cast(),
80 };
81 }
82 let (sender, receiver) = mpsc::channel();
83 let handler: IActivateAudioInterfaceCompletionHandler = ActivationHandler { sender }.into();
84 let _operation = unsafe {
85 ActivateAudioInterfaceAsync(VIRTUAL_AUDIO_DEVICE_PROCESS_LOOPBACK, &IAudioClient::IID, Some(&raw const *variant), &handler)
86 }
87 .map_err(|error| audio_error("activate process loopback", error))?;
88 receiver
89 .recv_timeout(ACTIVATION_WAIT)
90 .map_err(|_| Error::Audio("process loopback activation timed out".into()))?
91 .map(|client| client.0)
92 .map_err(|error| audio_error("process loopback activation", error))
93 }
94
95 fn initialise(client: &IAudioClient) -> Result<(IAudioCaptureClient, HANDLE)> {
96 let block_align = CHANNELS * BITS / 8;
97 let format = WAVEFORMATEX {
98 wFormatTag: PCM_TAG,
99 nChannels: CHANNELS,
100 nSamplesPerSec: SAMPLE_RATE,
101 nAvgBytesPerSec: SAMPLE_RATE * u32::from(block_align),
102 nBlockAlign: block_align,
103 wBitsPerSample: BITS,
104 cbSize: 0,
105 };
106 let flags = AUDCLNT_STREAMFLAGS_LOOPBACK
107 | AUDCLNT_STREAMFLAGS_EVENTCALLBACK
108 | AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM
109 | AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY;
110 unsafe {
111 client
112 .Initialize(AUDCLNT_SHAREMODE_SHARED, flags, 0, 0, &raw const format, None)
113 .map_err(|error| audio_error("initialize loopback", error))?;
114 let event = CreateEventW(None, false, false, None).map_err(|error| audio_error("event", error))?;
115 client.SetEventHandle(event).map_err(|error| audio_error("event handle", error))?;
116 let capture = client.GetService::<IAudioCaptureClient>().map_err(|error| audio_error("capture service", error))?;
117 client.Start().map_err(|error| audio_error("start loopback", error))?;
118 Ok((capture, event))
119 }
120 }
121
122 fn drain(capture: &IAudioCaptureClient, queue: &SampleQueue) -> windows::core::Result<()> {
123 unsafe {
124 while capture.GetNextPacketSize()? > 0 {
125 let mut data = std::ptr::null_mut();
126 let mut frames = 0u32;
127 let mut flags = 0u32;
128 capture.GetBuffer(&mut data, &mut frames, &mut flags, None, None)?;
129 let mono: Vec<i16> = if flags & AUDCLNT_BUFFERFLAGS_SILENT.0 as u32 != 0 || data.is_null() {
130 vec![0; frames as usize]
131 } else {
132 let pairs = std::slice::from_raw_parts(data.cast::<i16>(), frames as usize * usize::from(CHANNELS));
133 pairs.chunks_exact(usize::from(CHANNELS)).map(|pair| ((i32::from(pair[0]) + i32::from(pair[1])) / 2) as i16).collect()
134 };
135 capture.ReleaseBuffer(frames)?;
136 queue.push(&mono);
137 }
138 }
139 Ok(())
140 }
141
142 pub fn start_process_loopback(queue: SampleQueue, own_process_id: u32) -> Result<Capture> {
143 let (ready_sender, ready) = mpsc::channel::<Result<()>>();
144 let capture = Capture::spawn_thread("process-loopback", move |stop| {
145 unsafe {
146 let _ = CoInitializeEx(None, COINIT_MULTITHREADED);
147 }
148 let started = activate_excluding(own_process_id).and_then(|client| initialise(&client).map(|(capture, event)| (client, capture, event)));
149 match started {
150 Ok((client, capture, event)) => {
151 let _ = ready_sender.send(Ok(()));
152 while !stop.load(std::sync::atomic::Ordering::SeqCst) {
153 let waited = unsafe { WaitForSingleObject(event, EVENT_WAIT_MS) };
154 if waited == WAIT_OBJECT_0 && drain(&capture, &queue).is_err() {
155 break;
156 }
157 }
158 unsafe {
159 let _ = client.Stop();
160 let _ = CloseHandle(event);
161 }
162 }
163 Err(error) => {
164 let _ = ready_sender.send(Err(error));
165 }
166 }
167 unsafe { CoUninitialize() };
168 })
169 .map_err(|error| audio_error("loopback thread", error))?;
170 ready.recv().map_err(|_| Error::Audio("loopback thread ended".into()))??;
171 Ok(capture)
172 }
@@ -0,0 +1,172 @@
1use std::mem::{ManuallyDrop, size_of};
2use std::sync::mpsc;
3use std::time::Duration;
4
5use windows::Win32::Foundation::{CloseHandle, E_FAIL, HANDLE, WAIT_OBJECT_0};
6use windows::Win32::Media::Audio::{
7 AUDCLNT_BUFFERFLAGS_SILENT, AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM, AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
8 AUDCLNT_STREAMFLAGS_LOOPBACK, AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY, AUDIOCLIENT_ACTIVATION_PARAMS,
9 AUDIOCLIENT_ACTIVATION_PARAMS_0, AUDIOCLIENT_ACTIVATION_TYPE_PROCESS_LOOPBACK, AUDIOCLIENT_PROCESS_LOOPBACK_PARAMS,
10 ActivateAudioInterfaceAsync, IActivateAudioInterfaceAsyncOperation, IActivateAudioInterfaceCompletionHandler,
11 IActivateAudioInterfaceCompletionHandler_Impl, IAudioCaptureClient, IAudioClient, PROCESS_LOOPBACK_MODE_EXCLUDE_TARGET_PROCESS_TREE,
12 VIRTUAL_AUDIO_DEVICE_PROCESS_LOOPBACK, WAVEFORMATEX,
13};
14use windows::Win32::System::Com::StructuredStorage::PROPVARIANT;
15use windows::Win32::System::Com::{BLOB, COINIT_MULTITHREADED, CoInitializeEx, CoUninitialize, IAgileObject, IAgileObject_Impl};
16use windows::Win32::System::Threading::{CreateEventW, WaitForSingleObject};
17use windows::Win32::System::Variant::VT_BLOB;
18use windows::core::{Interface, Ref};
19use windows_core::implement;
20
21use crate::audio::SAMPLE_RATE;
22use crate::capture::Capture;
23use crate::error::{Error, Result};
24use crate::pcm::SampleQueue;
25
26const CHANNELS: u16 = 2;
27const BITS: u16 = 16;
28const ACTIVATION_WAIT: Duration = Duration::from_secs(5);
29const EVENT_WAIT_MS: u32 = 100;
30const PCM_TAG: u16 = 1;
31
32struct ActivatedClient(IAudioClient);
33
34unsafe impl Send for ActivatedClient {}
35
36#[implement(IActivateAudioInterfaceCompletionHandler, IAgileObject)]
37struct ActivationHandler {
38 sender: mpsc::Sender<windows::core::Result<ActivatedClient>>,
39}
40
41impl IAgileObject_Impl for ActivationHandler_Impl {}
42
43impl IActivateAudioInterfaceCompletionHandler_Impl for ActivationHandler_Impl {
44 fn ActivateCompleted(&self, operation: Ref<IActivateAudioInterfaceAsyncOperation>) -> windows::core::Result<()> {
45 let activated = (|| unsafe {
46 let operation = operation.ok()?;
47 let mut result = windows::core::HRESULT(0);
48 let mut unknown = None;
49 operation.GetActivateResult(&mut result, &mut unknown)?;
50 result.ok()?;
51 let unknown: windows::core::IUnknown = unknown.ok_or_else(|| windows::core::Error::from(E_FAIL))?;
52 unknown.cast::<IAudioClient>().map(ActivatedClient)
53 })();
54 let _ = self.sender.send(activated);
55 Ok(())
56 }
57}
58
59fn audio_error(what: &str, error: impl std::fmt::Display) -> Error {
60 Error::Audio(format!("{what}: {error}"))
61}
62
63fn activate_excluding(process_id: u32) -> Result<IAudioClient> {
64 let mut parameters = AUDIOCLIENT_ACTIVATION_PARAMS {
65 ActivationType: AUDIOCLIENT_ACTIVATION_TYPE_PROCESS_LOOPBACK,
66 Anonymous: AUDIOCLIENT_ACTIVATION_PARAMS_0 {
67 ProcessLoopbackParams: AUDIOCLIENT_PROCESS_LOOPBACK_PARAMS {
68 TargetProcessId: process_id,
69 ProcessLoopbackMode: PROCESS_LOOPBACK_MODE_EXCLUDE_TARGET_PROCESS_TREE,
70 },
71 },
72 };
73 let mut variant = ManuallyDrop::new(PROPVARIANT::default());
74 unsafe {
75 let inner = &mut *variant.Anonymous.Anonymous;
76 inner.vt = VT_BLOB;
77 inner.Anonymous.blob = BLOB {
78 cbSize: size_of::<AUDIOCLIENT_ACTIVATION_PARAMS>() as u32,
79 pBlobData: (&raw mut parameters).cast(),
80 };
81 }
82 let (sender, receiver) = mpsc::channel();
83 let handler: IActivateAudioInterfaceCompletionHandler = ActivationHandler { sender }.into();
84 let _operation = unsafe {
85 ActivateAudioInterfaceAsync(VIRTUAL_AUDIO_DEVICE_PROCESS_LOOPBACK, &IAudioClient::IID, Some(&raw const *variant), &handler)
86 }
87 .map_err(|error| audio_error("activate process loopback", error))?;
88 receiver
89 .recv_timeout(ACTIVATION_WAIT)
90 .map_err(|_| Error::Audio("process loopback activation timed out".into()))?
91 .map(|client| client.0)
92 .map_err(|error| audio_error("process loopback activation", error))
93}
94
95fn initialise(client: &IAudioClient) -> Result<(IAudioCaptureClient, HANDLE)> {
96 let block_align = CHANNELS * BITS / 8;
97 let format = WAVEFORMATEX {
98 wFormatTag: PCM_TAG,
99 nChannels: CHANNELS,
100 nSamplesPerSec: SAMPLE_RATE,
101 nAvgBytesPerSec: SAMPLE_RATE * u32::from(block_align),
102 nBlockAlign: block_align,
103 wBitsPerSample: BITS,
104 cbSize: 0,
105 };
106 let flags = AUDCLNT_STREAMFLAGS_LOOPBACK
107 | AUDCLNT_STREAMFLAGS_EVENTCALLBACK
108 | AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM
109 | AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY;
110 unsafe {
111 client
112 .Initialize(AUDCLNT_SHAREMODE_SHARED, flags, 0, 0, &raw const format, None)
113 .map_err(|error| audio_error("initialize loopback", error))?;
114 let event = CreateEventW(None, false, false, None).map_err(|error| audio_error("event", error))?;
115 client.SetEventHandle(event).map_err(|error| audio_error("event handle", error))?;
116 let capture = client.GetService::<IAudioCaptureClient>().map_err(|error| audio_error("capture service", error))?;
117 client.Start().map_err(|error| audio_error("start loopback", error))?;
118 Ok((capture, event))
119 }
120}
121
122fn drain(capture: &IAudioCaptureClient, queue: &SampleQueue) -> windows::core::Result<()> {
123 unsafe {
124 while capture.GetNextPacketSize()? > 0 {
125 let mut data = std::ptr::null_mut();
126 let mut frames = 0u32;
127 let mut flags = 0u32;
128 capture.GetBuffer(&mut data, &mut frames, &mut flags, None, None)?;
129 let mono: Vec<i16> = if flags & AUDCLNT_BUFFERFLAGS_SILENT.0 as u32 != 0 || data.is_null() {
130 vec![0; frames as usize]
131 } else {
132 let pairs = std::slice::from_raw_parts(data.cast::<i16>(), frames as usize * usize::from(CHANNELS));
133 pairs.chunks_exact(usize::from(CHANNELS)).map(|pair| ((i32::from(pair[0]) + i32::from(pair[1])) / 2) as i16).collect()
134 };
135 capture.ReleaseBuffer(frames)?;
136 queue.push(&mono);
137 }
138 }
139 Ok(())
140}
141
142pub fn start_process_loopback(queue: SampleQueue, own_process_id: u32) -> Result<Capture> {
143 let (ready_sender, ready) = mpsc::channel::<Result<()>>();
144 let capture = Capture::spawn_thread("process-loopback", move |stop| {
145 unsafe {
146 let _ = CoInitializeEx(None, COINIT_MULTITHREADED);
147 }
148 let started = activate_excluding(own_process_id).and_then(|client| initialise(&client).map(|(capture, event)| (client, capture, event)));
149 match started {
150 Ok((client, capture, event)) => {
151 let _ = ready_sender.send(Ok(()));
152 while !stop.load(std::sync::atomic::Ordering::SeqCst) {
153 let waited = unsafe { WaitForSingleObject(event, EVENT_WAIT_MS) };
154 if waited == WAIT_OBJECT_0 && drain(&capture, &queue).is_err() {
155 break;
156 }
157 }
158 unsafe {
159 let _ = client.Stop();
160 let _ = CloseHandle(event);
161 }
162 }
163 Err(error) => {
164 let _ = ready_sender.send(Err(error));
165 }
166 }
167 unsafe { CoUninitialize() };
168 })
169 .map_err(|error| audio_error("loopback thread", error))?;
170 ready.recv().map_err(|_| Error::Audio("loopback thread ended".into()))??;
171 Ok(capture)
172}
crates/calling/src/mixer.rs added +43 −0
@@ -0,0 +1,43 @@
1 use crate::audio::FRAME_SAMPLES;
2
3 pub fn mix_frames(microphone: &[i16], computer: &[i16], microphone_muted: bool) -> Vec<i16> {
4 (0..FRAME_SAMPLES)
5 .map(|index| {
6 let mic = if microphone_muted { 0 } else { i32::from(microphone.get(index).copied().unwrap_or(0)) };
7 let sound = i32::from(computer.get(index).copied().unwrap_or(0));
8 (mic + sound).clamp(i32::from(i16::MIN), i32::from(i16::MAX)) as i16
9 })
10 .collect()
11 }
12
13 #[cfg(test)]
14 mod tests {
15 use super::*;
16
17 #[test]
18 fn the_two_sources_are_summed() {
19 let mixed = mix_frames(&[100; FRAME_SAMPLES], &[-30; FRAME_SAMPLES], false);
20 assert_eq!(mixed.len(), FRAME_SAMPLES);
21 assert!(mixed.iter().all(|&sample| sample == 70));
22 }
23
24 #[test]
25 fn the_sum_clips_instead_of_wrapping() {
26 let loud = [i16::MAX - 10; FRAME_SAMPLES];
27 assert!(mix_frames(&loud, &loud, false).iter().all(|&sample| sample == i16::MAX));
28 let low = [i16::MIN + 10; FRAME_SAMPLES];
29 assert!(mix_frames(&low, &low, false).iter().all(|&sample| sample == i16::MIN));
30 }
31
32 #[test]
33 fn muting_drops_only_the_microphone() {
34 let mixed = mix_frames(&[500; FRAME_SAMPLES], &[200; FRAME_SAMPLES], true);
35 assert!(mixed.iter().all(|&sample| sample == 200));
36 }
37
38 #[test]
39 fn a_short_source_counts_as_silence_for_the_rest() {
40 let mixed = mix_frames(&[10; 4], &[1; FRAME_SAMPLES], false);
41 assert_eq!(&mixed[..5], &[11, 11, 11, 11, 1]);
42 }
43 }
@@ -0,0 +1,43 @@
1use crate::audio::FRAME_SAMPLES;
2
3pub fn mix_frames(microphone: &[i16], computer: &[i16], microphone_muted: bool) -> Vec<i16> {
4 (0..FRAME_SAMPLES)
5 .map(|index| {
6 let mic = if microphone_muted { 0 } else { i32::from(microphone.get(index).copied().unwrap_or(0)) };
7 let sound = i32::from(computer.get(index).copied().unwrap_or(0));
8 (mic + sound).clamp(i32::from(i16::MIN), i32::from(i16::MAX)) as i16
9 })
10 .collect()
11}
12
13#[cfg(test)]
14mod tests {
15 use super::*;
16
17 #[test]
18 fn the_two_sources_are_summed() {
19 let mixed = mix_frames(&[100; FRAME_SAMPLES], &[-30; FRAME_SAMPLES], false);
20 assert_eq!(mixed.len(), FRAME_SAMPLES);
21 assert!(mixed.iter().all(|&sample| sample == 70));
22 }
23
24 #[test]
25 fn the_sum_clips_instead_of_wrapping() {
26 let loud = [i16::MAX - 10; FRAME_SAMPLES];
27 assert!(mix_frames(&loud, &loud, false).iter().all(|&sample| sample == i16::MAX));
28 let low = [i16::MIN + 10; FRAME_SAMPLES];
29 assert!(mix_frames(&low, &low, false).iter().all(|&sample| sample == i16::MIN));
30 }
31
32 #[test]
33 fn muting_drops_only_the_microphone() {
34 let mixed = mix_frames(&[500; FRAME_SAMPLES], &[200; FRAME_SAMPLES], true);
35 assert!(mixed.iter().all(|&sample| sample == 200));
36 }
37
38 #[test]
39 fn a_short_source_counts_as_silence_for_the_rest() {
40 let mixed = mix_frames(&[10; 4], &[1; FRAME_SAMPLES], false);
41 assert_eq!(&mixed[..5], &[11, 11, 11, 11, 1]);
42 }
43}
crates/calling/src/pcm.rs added +110 −0
@@ -0,0 +1,110 @@
1 use std::collections::VecDeque;
2 use std::sync::{Arc, Mutex};
3
4 use crate::audio::{FRAME_SAMPLES, SAMPLE_RATE};
5
6 const MAX_QUEUED_SAMPLES: usize = SAMPLE_RATE as usize / 5;
7
8 #[derive(Clone, Default)]
9 pub struct SampleQueue {
10 samples: Arc<Mutex<VecDeque<i16>>>,
11 }
12
13 impl SampleQueue {
14 pub fn push(&self, samples: &[i16]) {
15 let mut queued = self.samples.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
16 queued.extend(samples.iter().copied());
17 let excess = queued.len().saturating_sub(MAX_QUEUED_SAMPLES);
18 queued.drain(..excess);
19 }
20
21 pub fn next_frame(&self) -> (Vec<i16>, bool) {
22 let mut queued = self.samples.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
23 let available = queued.len().min(FRAME_SAMPLES);
24 let mut frame: Vec<i16> = queued.drain(..available).collect();
25 frame.resize(FRAME_SAMPLES, 0);
26 (frame, available > 0)
27 }
28 }
29
30 /// Downmixes interleaved floats to mono and converts them to 48 kHz with linear interpolation.
31 pub struct MonoResampler {
32 step: f64,
33 position: f64,
34 previous: f32,
35 }
36
37 impl MonoResampler {
38 pub fn new(source_rate: u32) -> Self {
39 MonoResampler {
40 step: f64::from(source_rate) / f64::from(SAMPLE_RATE),
41 position: 0.0,
42 previous: 0.0,
43 }
44 }
45
46 pub fn convert(&mut self, interleaved: &[f32], channels: usize, output: &mut Vec<i16>) {
47 let channels = channels.max(1);
48 for frame in interleaved.chunks_exact(channels) {
49 let current = frame.iter().sum::<f32>() / channels as f32;
50 while self.position < 1.0 {
51 let value = self.previous + (current - self.previous) * self.position as f32;
52 output.push((value.clamp(-1.0, 1.0) * f32::from(i16::MAX)) as i16);
53 self.position += self.step;
54 }
55 self.position -= 1.0;
56 self.previous = current;
57 }
58 }
59 }
60
61 pub fn i16_to_f32(samples: &[i16]) -> Vec<f32> {
62 samples.iter().map(|&sample| f32::from(sample) / f32::from(i16::MAX)).collect()
63 }
64
65 #[cfg(test)]
66 mod tests {
67 use super::*;
68
69 #[test]
70 fn frames_come_out_in_order_and_pad_with_silence() {
71 let queue = SampleQueue::default();
72 queue.push(&[1, 2, 3]);
73 let (frame, had_data) = queue.next_frame();
74 assert!(had_data);
75 assert_eq!(frame.len(), FRAME_SAMPLES);
76 assert_eq!(&frame[..4], &[1, 2, 3, 0]);
77 assert!(!queue.next_frame().1);
78 }
79
80 #[test]
81 fn the_queue_drops_the_oldest_samples_when_the_reader_stalls() {
82 let queue = SampleQueue::default();
83 queue.push(&vec![1; MAX_QUEUED_SAMPLES]);
84 queue.push(&vec![2; FRAME_SAMPLES]);
85 let (frame, _) = queue.next_frame();
86 assert_eq!(frame[0], 1);
87 let mut last = frame;
88 for _ in 1..MAX_QUEUED_SAMPLES / FRAME_SAMPLES {
89 last = queue.next_frame().0;
90 }
91 assert_eq!(last[FRAME_SAMPLES - 1], 2);
92 }
93
94 #[test]
95 fn stereo_at_24_khz_becomes_mono_at_48_khz() {
96 let mut resampler = MonoResampler::new(24_000);
97 let mut output = Vec::new();
98 resampler.convert(&[0.5, 0.5].repeat(240), 2, &mut output);
99 assert_eq!(output.len(), 480);
100 assert!(output[10..].iter().all(|&sample| (sample - (0.5 * f32::from(i16::MAX)) as i16).abs() < 2));
101 }
102
103 #[test]
104 fn the_native_rate_passes_through() {
105 let mut resampler = MonoResampler::new(48_000);
106 let mut output = Vec::new();
107 resampler.convert(&[0.25; 480], 1, &mut output);
108 assert_eq!(output.len(), 480);
109 }
110 }
@@ -0,0 +1,110 @@
1use std::collections::VecDeque;
2use std::sync::{Arc, Mutex};
3
4use crate::audio::{FRAME_SAMPLES, SAMPLE_RATE};
5
6const MAX_QUEUED_SAMPLES: usize = SAMPLE_RATE as usize / 5;
7
8#[derive(Clone, Default)]
9pub struct SampleQueue {
10 samples: Arc<Mutex<VecDeque<i16>>>,
11}
12
13impl SampleQueue {
14 pub fn push(&self, samples: &[i16]) {
15 let mut queued = self.samples.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
16 queued.extend(samples.iter().copied());
17 let excess = queued.len().saturating_sub(MAX_QUEUED_SAMPLES);
18 queued.drain(..excess);
19 }
20
21 pub fn next_frame(&self) -> (Vec<i16>, bool) {
22 let mut queued = self.samples.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
23 let available = queued.len().min(FRAME_SAMPLES);
24 let mut frame: Vec<i16> = queued.drain(..available).collect();
25 frame.resize(FRAME_SAMPLES, 0);
26 (frame, available > 0)
27 }
28}
29
30/// Downmixes interleaved floats to mono and converts them to 48 kHz with linear interpolation.
31pub struct MonoResampler {
32 step: f64,
33 position: f64,
34 previous: f32,
35}
36
37impl MonoResampler {
38 pub fn new(source_rate: u32) -> Self {
39 MonoResampler {
40 step: f64::from(source_rate) / f64::from(SAMPLE_RATE),
41 position: 0.0,
42 previous: 0.0,
43 }
44 }
45
46 pub fn convert(&mut self, interleaved: &[f32], channels: usize, output: &mut Vec<i16>) {
47 let channels = channels.max(1);
48 for frame in interleaved.chunks_exact(channels) {
49 let current = frame.iter().sum::<f32>() / channels as f32;
50 while self.position < 1.0 {
51 let value = self.previous + (current - self.previous) * self.position as f32;
52 output.push((value.clamp(-1.0, 1.0) * f32::from(i16::MAX)) as i16);
53 self.position += self.step;
54 }
55 self.position -= 1.0;
56 self.previous = current;
57 }
58 }
59}
60
61pub fn i16_to_f32(samples: &[i16]) -> Vec<f32> {
62 samples.iter().map(|&sample| f32::from(sample) / f32::from(i16::MAX)).collect()
63}
64
65#[cfg(test)]
66mod tests {
67 use super::*;
68
69 #[test]
70 fn frames_come_out_in_order_and_pad_with_silence() {
71 let queue = SampleQueue::default();
72 queue.push(&[1, 2, 3]);
73 let (frame, had_data) = queue.next_frame();
74 assert!(had_data);
75 assert_eq!(frame.len(), FRAME_SAMPLES);
76 assert_eq!(&frame[..4], &[1, 2, 3, 0]);
77 assert!(!queue.next_frame().1);
78 }
79
80 #[test]
81 fn the_queue_drops_the_oldest_samples_when_the_reader_stalls() {
82 let queue = SampleQueue::default();
83 queue.push(&vec![1; MAX_QUEUED_SAMPLES]);
84 queue.push(&vec![2; FRAME_SAMPLES]);
85 let (frame, _) = queue.next_frame();
86 assert_eq!(frame[0], 1);
87 let mut last = frame;
88 for _ in 1..MAX_QUEUED_SAMPLES / FRAME_SAMPLES {
89 last = queue.next_frame().0;
90 }
91 assert_eq!(last[FRAME_SAMPLES - 1], 2);
92 }
93
94 #[test]
95 fn stereo_at_24_khz_becomes_mono_at_48_khz() {
96 let mut resampler = MonoResampler::new(24_000);
97 let mut output = Vec::new();
98 resampler.convert(&[0.5, 0.5].repeat(240), 2, &mut output);
99 assert_eq!(output.len(), 480);
100 assert!(output[10..].iter().all(|&sample| (sample - (0.5 * f32::from(i16::MAX)) as i16).abs() < 2));
101 }
102
103 #[test]
104 fn the_native_rate_passes_through() {
105 let mut resampler = MonoResampler::new(48_000);
106 let mut output = Vec::new();
107 resampler.convert(&[0.25; 480], 1, &mut output);
108 assert_eq!(output.len(), 480);
109 }
110}
crates/calling/src/reaction.rs added +145 −0
@@ -0,0 +1,145 @@
1 use serde_json::{Value, json};
2
3 pub const DEFAULT_SKIN_TONE: u8 = 2;
4 const REACTION_TYPE: &str = "Reaction";
5
6 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
7 pub enum Reaction {
8 Like,
9 Heart,
10 Applause,
11 Laugh,
12 Surprised,
13 }
14
15 impl Reaction {
16 pub const ALL: [Reaction; 5] = [Reaction::Like, Reaction::Heart, Reaction::Applause, Reaction::Laugh, Reaction::Surprised];
17
18 pub fn name(self) -> &'static str {
19 match self {
20 Reaction::Like => "like",
21 Reaction::Heart => "heart",
22 Reaction::Applause => "applause",
23 Reaction::Laugh => "laugh",
24 Reaction::Surprised => "surprised",
25 }
26 }
27
28 pub fn from_name(name: &str) -> Option<Reaction> {
29 Reaction::ALL.into_iter().find(|reaction| reaction.name() == name)
30 }
31
32 fn takes_skin_tone(self) -> bool {
33 matches!(self, Reaction::Like | Reaction::Applause)
34 }
35 }
36
37 #[derive(Debug, Clone, PartialEq, Eq)]
38 pub struct ReactionEvent {
39 pub mri: String,
40 pub reaction: Reaction,
41 pub count: u32,
42 }
43
44 pub fn reaction_message(from: Value, reaction: Reaction, operation_id: &str, value_id: &str) -> Value {
45 let skin_tone = reaction.takes_skin_tone().then_some(DEFAULT_SKIN_TONE);
46 json!({
47 "from": from,
48 "messageContent": [{
49 "operationId": operation_id,
50 "type": REACTION_TYPE,
51 "scope": "all",
52 "to": [],
53 "payload": {"values": [{
54 "id": value_id,
55 "name": reaction.name(),
56 "count": 1,
57 "attributes": {"skinTone": skin_tone},
58 }]},
59 }],
60 })
61 }
62
63 pub fn parse_reactions(body: &Value) -> Vec<ReactionEvent> {
64 let items: Vec<&Value> = match body["messageContent"].as_array() {
65 Some(items) => items.iter().collect(),
66 None => vec![body],
67 };
68 items
69 .into_iter()
70 .filter(|item| item["type"].as_str() == Some(REACTION_TYPE))
71 .flat_map(|item| {
72 let mri = item["from"]["id"].as_str().or_else(|| body["from"]["id"].as_str()).unwrap_or_default();
73 item["payload"]["values"].as_array().into_iter().flatten().filter_map(move |value| {
74 Some(ReactionEvent {
75 mri: mri.to_owned(),
76 reaction: Reaction::from_name(value["name"].as_str()?)?,
77 count: value["count"].as_u64().map_or(1, |count| u32::try_from(count).unwrap_or(u32::MAX)),
78 })
79 })
80 })
81 .filter(|event| !event.mri.is_empty())
82 .collect()
83 }
84
85 #[cfg(test)]
86 mod tests {
87 use super::*;
88
89 #[test]
90 fn the_send_body_has_one_reaction_value_with_the_skin_tone_only_where_it_applies() {
91 let from = json!({"id": "8:orgid:me"});
92 let like = reaction_message(from.clone(), Reaction::Like, "op-1", "val-1");
93 let item = &like["messageContent"][0];
94 assert_eq!(like["from"]["id"], "8:orgid:me");
95 assert_eq!(item["type"], "Reaction");
96 assert_eq!(item["scope"], "all");
97 assert_eq!(item["operationId"], "op-1");
98 assert_eq!(item["payload"]["values"][0]["name"], "like");
99 assert_eq!(item["payload"]["values"][0]["count"], 1);
100 assert_eq!(item["payload"]["values"][0]["attributes"]["skinTone"], DEFAULT_SKIN_TONE);
101 let heart = reaction_message(from, Reaction::Heart, "op-2", "val-2");
102 assert!(heart["messageContent"][0]["payload"]["values"][0]["attributes"]["skinTone"].is_null());
103 }
104
105 #[test]
106 fn every_reaction_name_round_trips() {
107 for reaction in Reaction::ALL {
108 assert_eq!(Reaction::from_name(reaction.name()), Some(reaction));
109 }
110 assert_eq!(Reaction::from_name("confetti"), None);
111 }
112
113 #[test]
114 fn a_single_received_reaction_is_parsed() {
115 let body = json!({
116 "from": {"id": "8:orgid:a", "displayName": "Ana"},
117 "type": "Reaction",
118 "payload": {"values": [{"name": "applause", "count": 2, "attributes": {"skinTone": "2"}}]},
119 "operationId": "op",
120 });
121 assert_eq!(parse_reactions(&body), vec![ReactionEvent { mri: "8:orgid:a".into(), reaction: Reaction::Applause, count: 2 }]);
122 }
123
124 #[test]
125 fn several_message_contents_and_foreign_types_are_handled() {
126 let body = json!({
127 "from": {"id": "8:orgid:a"},
128 "messageContent": [
129 {"type": "Reaction", "payload": {"values": [{"name": "heart"}, {"name": "unknown"}]}},
130 {"type": "Typing", "payload": {"values": [{"name": "like"}]}},
131 {"type": "Reaction", "from": {"id": "8:orgid:b"}, "payload": {"values": [{"name": "laugh", "count": 1}]}},
132 ],
133 });
134 let events = parse_reactions(&body);
135 assert_eq!(events.len(), 2);
136 assert_eq!(events[0], ReactionEvent { mri: "8:orgid:a".into(), reaction: Reaction::Heart, count: 1 });
137 assert_eq!(events[1].mri, "8:orgid:b");
138 }
139
140 #[test]
141 fn a_message_without_a_sender_is_ignored() {
142 let body = json!({"type": "Reaction", "payload": {"values": [{"name": "like"}]}});
143 assert!(parse_reactions(&body).is_empty());
144 }
145 }
@@ -0,0 +1,145 @@
1use serde_json::{Value, json};
2
3pub const DEFAULT_SKIN_TONE: u8 = 2;
4const REACTION_TYPE: &str = "Reaction";
5
6#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7pub enum Reaction {
8 Like,
9 Heart,
10 Applause,
11 Laugh,
12 Surprised,
13}
14
15impl Reaction {
16 pub const ALL: [Reaction; 5] = [Reaction::Like, Reaction::Heart, Reaction::Applause, Reaction::Laugh, Reaction::Surprised];
17
18 pub fn name(self) -> &'static str {
19 match self {
20 Reaction::Like => "like",
21 Reaction::Heart => "heart",
22 Reaction::Applause => "applause",
23 Reaction::Laugh => "laugh",
24 Reaction::Surprised => "surprised",
25 }
26 }
27
28 pub fn from_name(name: &str) -> Option<Reaction> {
29 Reaction::ALL.into_iter().find(|reaction| reaction.name() == name)
30 }
31
32 fn takes_skin_tone(self) -> bool {
33 matches!(self, Reaction::Like | Reaction::Applause)
34 }
35}
36
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct ReactionEvent {
39 pub mri: String,
40 pub reaction: Reaction,
41 pub count: u32,
42}
43
44pub fn reaction_message(from: Value, reaction: Reaction, operation_id: &str, value_id: &str) -> Value {
45 let skin_tone = reaction.takes_skin_tone().then_some(DEFAULT_SKIN_TONE);
46 json!({
47 "from": from,
48 "messageContent": [{
49 "operationId": operation_id,
50 "type": REACTION_TYPE,
51 "scope": "all",
52 "to": [],
53 "payload": {"values": [{
54 "id": value_id,
55 "name": reaction.name(),
56 "count": 1,
57 "attributes": {"skinTone": skin_tone},
58 }]},
59 }],
60 })
61}
62
63pub fn parse_reactions(body: &Value) -> Vec<ReactionEvent> {
64 let items: Vec<&Value> = match body["messageContent"].as_array() {
65 Some(items) => items.iter().collect(),
66 None => vec![body],
67 };
68 items
69 .into_iter()
70 .filter(|item| item["type"].as_str() == Some(REACTION_TYPE))
71 .flat_map(|item| {
72 let mri = item["from"]["id"].as_str().or_else(|| body["from"]["id"].as_str()).unwrap_or_default();
73 item["payload"]["values"].as_array().into_iter().flatten().filter_map(move |value| {
74 Some(ReactionEvent {
75 mri: mri.to_owned(),
76 reaction: Reaction::from_name(value["name"].as_str()?)?,
77 count: value["count"].as_u64().map_or(1, |count| u32::try_from(count).unwrap_or(u32::MAX)),
78 })
79 })
80 })
81 .filter(|event| !event.mri.is_empty())
82 .collect()
83}
84
85#[cfg(test)]
86mod tests {
87 use super::*;
88
89 #[test]
90 fn the_send_body_has_one_reaction_value_with_the_skin_tone_only_where_it_applies() {
91 let from = json!({"id": "8:orgid:me"});
92 let like = reaction_message(from.clone(), Reaction::Like, "op-1", "val-1");
93 let item = &like["messageContent"][0];
94 assert_eq!(like["from"]["id"], "8:orgid:me");
95 assert_eq!(item["type"], "Reaction");
96 assert_eq!(item["scope"], "all");
97 assert_eq!(item["operationId"], "op-1");
98 assert_eq!(item["payload"]["values"][0]["name"], "like");
99 assert_eq!(item["payload"]["values"][0]["count"], 1);
100 assert_eq!(item["payload"]["values"][0]["attributes"]["skinTone"], DEFAULT_SKIN_TONE);
101 let heart = reaction_message(from, Reaction::Heart, "op-2", "val-2");
102 assert!(heart["messageContent"][0]["payload"]["values"][0]["attributes"]["skinTone"].is_null());
103 }
104
105 #[test]
106 fn every_reaction_name_round_trips() {
107 for reaction in Reaction::ALL {
108 assert_eq!(Reaction::from_name(reaction.name()), Some(reaction));
109 }
110 assert_eq!(Reaction::from_name("confetti"), None);
111 }
112
113 #[test]
114 fn a_single_received_reaction_is_parsed() {
115 let body = json!({
116 "from": {"id": "8:orgid:a", "displayName": "Ana"},
117 "type": "Reaction",
118 "payload": {"values": [{"name": "applause", "count": 2, "attributes": {"skinTone": "2"}}]},
119 "operationId": "op",
120 });
121 assert_eq!(parse_reactions(&body), vec![ReactionEvent { mri: "8:orgid:a".into(), reaction: Reaction::Applause, count: 2 }]);
122 }
123
124 #[test]
125 fn several_message_contents_and_foreign_types_are_handled() {
126 let body = json!({
127 "from": {"id": "8:orgid:a"},
128 "messageContent": [
129 {"type": "Reaction", "payload": {"values": [{"name": "heart"}, {"name": "unknown"}]}},
130 {"type": "Typing", "payload": {"values": [{"name": "like"}]}},
131 {"type": "Reaction", "from": {"id": "8:orgid:b"}, "payload": {"values": [{"name": "laugh", "count": 1}]}},
132 ],
133 });
134 let events = parse_reactions(&body);
135 assert_eq!(events.len(), 2);
136 assert_eq!(events[0], ReactionEvent { mri: "8:orgid:a".into(), reaction: Reaction::Heart, count: 1 });
137 assert_eq!(events[1].mri, "8:orgid:b");
138 }
139
140 #[test]
141 fn a_message_without_a_sender_is_ignored() {
142 let body = json!({"type": "Reaction", "payload": {"values": [{"name": "like"}]}});
143 assert!(parse_reactions(&body).is_empty());
144 }
145}
crates/calling/src/roster.rs +70 −0
@@ -5,6 +5,13 @@ const AUDIO: &str = "audio";
5 5 const VIDEO: &str = "video";
6 6 const SCREEN: &str = "applicationsharing-video";
7 7 const SENDING_DIRECTIONS: [&str; 2] = ["sendonly", "sendrecv"];
8 const RAISE_HANDS: &str = "raiseHands";
9
10 #[derive(Debug, Clone, PartialEq, Eq)]
11 pub struct RaisedHand {
12 pub state_id: String,
13 pub rank: u64,
14 }
8 15
9 16 #[derive(Debug, Clone, PartialEq, Eq)]
10 17 pub struct Member {
@@ -16,6 +23,7 @@ pub struct Member {
16 23 pub video_source: Option<u32>,
17 24 pub screen_source: Option<u32>,
18 25 pub streams: Vec<String>,
26 pub hand: Option<RaisedHand>,
19 27 version: u64,
20 28 }
21 29
@@ -27,6 +35,7 @@ pub struct RosterEntry {
27 35 pub in_lobby: bool,
28 36 pub has_video: bool,
29 37 pub sharing: bool,
38 pub hand: Option<RaisedHand>,
30 39 }
31 40
32 41 #[derive(Debug, Clone, Default, PartialEq, Eq)]
@@ -50,6 +59,7 @@ impl Roster {
50 59 in_lobby: member.in_lobby,
51 60 has_video: member.video_source.is_some(),
52 61 sharing: member.screen_source.is_some(),
62 hand: member.hand.clone(),
53 63 })
54 64 .collect()
55 65 }
@@ -83,6 +93,10 @@ impl Roster {
83 93 *self != before
84 94 }
85 95
96 pub fn hand_of(&self, mri: &str) -> Option<&RaisedHand> {
97 self.members.iter().find(|member| member.mri == mri)?.hand.as_ref()
98 }
99
86 100 pub fn is_in_lobby(&self, mri: &str) -> Option<bool> {
87 101 self.members.iter().find(|member| member.mri == mri).map(|member| member.in_lobby)
88 102 }
@@ -147,10 +161,26 @@ fn member_from(mri: &str, participant: &Value, version: u64, previous: Option<&M
147 161 video_source: sending_source(&in_call, VIDEO),
148 162 screen_source: sending_source(&in_call, SCREEN),
149 163 streams: stream_summaries(&in_call),
164 hand: raised_hand(participant, &endpoints),
150 165 version,
151 166 }
152 167 }
153 168
169 fn raised_hand(participant: &Value, endpoints: &[&Value]) -> Option<RaisedHand> {
170 std::iter::once(participant)
171 .chain(endpoints.iter().copied())
172 .flat_map(|holder| holder["publishedStates"].as_array().into_iter().flatten())
173 .filter(|state| state["stateType"].as_str() == Some(RAISE_HANDS))
174 .find_map(|state| {
175 let state_id = match &state["stateId"] {
176 Value::String(text) => text.clone(),
177 Value::Null => return None,
178 other => other.to_string(),
179 };
180 Some(RaisedHand { state_id, rank: state["typeRank"].as_u64().unwrap_or(u64::MAX) })
181 })
182 }
183
154 184 fn stream_summaries(in_call: &[&&Value]) -> Vec<String> {
155 185 in_call
156 186 .iter()
@@ -318,6 +348,46 @@ mod tests {
318 348 assert!(entries.iter().find(|entry| entry.display_name == "Cy").unwrap().sharing);
319 349 }
320 350
351 fn with_hand(mut person: Value, state_id: &str, rank: u64) -> Value {
352 person["publishedStates"] = json!([
353 {"stateType": "spotlight", "stateId": "x", "typeRank": 1},
354 {"stateType": "raiseHands", "content": {"skinTone": 2}, "stateId": state_id, "typeRank": rank},
355 ]);
356 person
357 }
358
359 #[test]
360 fn published_states_carry_the_raised_hand_and_its_queue_rank() {
361 let mut roster = Roster::default();
362 roster.apply(&delta(json!({
363 "8:orgid:a": with_hand(participant("Ana", 1, "active", false, 201), "s-1", 2),
364 "8:orgid:b": with_hand(participant("Bo", 1, "active", false, 301), "s-2", 1),
365 "8:orgid:c": participant("Cy", 1, "active", false, 401),
366 })));
367 assert_eq!(roster.hand_of("8:orgid:a"), Some(&RaisedHand { state_id: "s-1".into(), rank: 2 }));
368 assert_eq!(roster.hand_of("8:orgid:b").map(|hand| hand.rank), Some(1));
369 assert_eq!(roster.hand_of("8:orgid:c"), None);
370 let entries = roster.entries();
371 assert!(entries.iter().find(|entry| entry.display_name == "Bo").unwrap().hand.is_some());
372 }
373
374 #[test]
375 fn lowering_removes_the_key_and_the_hand() {
376 let mut roster = Roster::default();
377 roster.apply(&delta(json!({"8:orgid:a": with_hand(participant("Ana", 1, "active", false, 201), "s-1", 1)})));
378 assert!(roster.apply(&delta(json!({"8:orgid:a": participant("Ana", 2, "active", false, 201)}))));
379 assert_eq!(roster.hand_of("8:orgid:a"), None);
380 }
381
382 #[test]
383 fn endpoint_level_published_states_count_too() {
384 let mut roster = Roster::default();
385 let mut person = participant("Ana", 1, "active", false, 201);
386 person["endpoints"]["ep"]["publishedStates"] = json!([{"stateType": "raiseHands", "stateId": 7, "typeRank": 3}]);
387 roster.apply(&delta(json!({"8:orgid:a": person})));
388 assert_eq!(roster.hand_of("8:orgid:a"), Some(&RaisedHand { state_id: "7".into(), rank: 3 }));
389 }
390
321 391 #[test]
322 392 fn missing_name_keeps_the_known_one() {
323 393 let mut roster = Roster::default();
@@ -5,6 +5,13 @@ const AUDIO: &str = "audio";
5const VIDEO: &str = "video";
5const VIDEO: &str = "video";
6const SCREEN: &str = "applicationsharing-video";
6const SCREEN: &str = "applicationsharing-video";
7const SENDING_DIRECTIONS: [&str; 2] = ["sendonly", "sendrecv"];
7const SENDING_DIRECTIONS: [&str; 2] = ["sendonly", "sendrecv"];
8const RAISE_HANDS: &str = "raiseHands";
9
10#[derive(Debug, Clone, PartialEq, Eq)]
11pub struct RaisedHand {
12 pub state_id: String,
13 pub rank: u64,
14}
8
15
9#[derive(Debug, Clone, PartialEq, Eq)]
16#[derive(Debug, Clone, PartialEq, Eq)]
10pub struct Member {
17pub struct Member {
@@ -16,6 +23,7 @@ pub struct Member {
16 pub video_source: Option<u32>,
23 pub video_source: Option<u32>,
17 pub screen_source: Option<u32>,
24 pub screen_source: Option<u32>,
18 pub streams: Vec<String>,
25 pub streams: Vec<String>,
26 pub hand: Option<RaisedHand>,
19 version: u64,
27 version: u64,
20}
28}
21
29
@@ -27,6 +35,7 @@ pub struct RosterEntry {
27 pub in_lobby: bool,
35 pub in_lobby: bool,
28 pub has_video: bool,
36 pub has_video: bool,
29 pub sharing: bool,
37 pub sharing: bool,
38 pub hand: Option<RaisedHand>,
30}
39}
31
40
32#[derive(Debug, Clone, Default, PartialEq, Eq)]
41#[derive(Debug, Clone, Default, PartialEq, Eq)]
@@ -50,6 +59,7 @@ impl Roster {
50 in_lobby: member.in_lobby,
59 in_lobby: member.in_lobby,
51 has_video: member.video_source.is_some(),
60 has_video: member.video_source.is_some(),
52 sharing: member.screen_source.is_some(),
61 sharing: member.screen_source.is_some(),
62 hand: member.hand.clone(),
53 })
63 })
54 .collect()
64 .collect()
55 }
65 }
@@ -83,6 +93,10 @@ impl Roster {
83 *self != before
93 *self != before
84 }
94 }
85
95
96 pub fn hand_of(&self, mri: &str) -> Option<&RaisedHand> {
97 self.members.iter().find(|member| member.mri == mri)?.hand.as_ref()
98 }
99
86 pub fn is_in_lobby(&self, mri: &str) -> Option<bool> {
100 pub fn is_in_lobby(&self, mri: &str) -> Option<bool> {
87 self.members.iter().find(|member| member.mri == mri).map(|member| member.in_lobby)
101 self.members.iter().find(|member| member.mri == mri).map(|member| member.in_lobby)
88 }
102 }
@@ -147,10 +161,26 @@ fn member_from(mri: &str, participant: &Value, version: u64, previous: Option<&M
147 video_source: sending_source(&in_call, VIDEO),
161 video_source: sending_source(&in_call, VIDEO),
148 screen_source: sending_source(&in_call, SCREEN),
162 screen_source: sending_source(&in_call, SCREEN),
149 streams: stream_summaries(&in_call),
163 streams: stream_summaries(&in_call),
164 hand: raised_hand(participant, &endpoints),
150 version,
165 version,
151 }
166 }
152}
167}
153
168
169fn raised_hand(participant: &Value, endpoints: &[&Value]) -> Option<RaisedHand> {
170 std::iter::once(participant)
171 .chain(endpoints.iter().copied())
172 .flat_map(|holder| holder["publishedStates"].as_array().into_iter().flatten())
173 .filter(|state| state["stateType"].as_str() == Some(RAISE_HANDS))
174 .find_map(|state| {
175 let state_id = match &state["stateId"] {
176 Value::String(text) => text.clone(),
177 Value::Null => return None,
178 other => other.to_string(),
179 };
180 Some(RaisedHand { state_id, rank: state["typeRank"].as_u64().unwrap_or(u64::MAX) })
181 })
182}
183
154fn stream_summaries(in_call: &[&&Value]) -> Vec<String> {
184fn stream_summaries(in_call: &[&&Value]) -> Vec<String> {
155 in_call
185 in_call
156 .iter()
186 .iter()
@@ -318,6 +348,46 @@ mod tests {
318 assert!(entries.iter().find(|entry| entry.display_name == "Cy").unwrap().sharing);
348 assert!(entries.iter().find(|entry| entry.display_name == "Cy").unwrap().sharing);
319 }
349 }
320
350
351 fn with_hand(mut person: Value, state_id: &str, rank: u64) -> Value {
352 person["publishedStates"] = json!([
353 {"stateType": "spotlight", "stateId": "x", "typeRank": 1},
354 {"stateType": "raiseHands", "content": {"skinTone": 2}, "stateId": state_id, "typeRank": rank},
355 ]);
356 person
357 }
358
359 #[test]
360 fn published_states_carry_the_raised_hand_and_its_queue_rank() {
361 let mut roster = Roster::default();
362 roster.apply(&delta(json!({
363 "8:orgid:a": with_hand(participant("Ana", 1, "active", false, 201), "s-1", 2),
364 "8:orgid:b": with_hand(participant("Bo", 1, "active", false, 301), "s-2", 1),
365 "8:orgid:c": participant("Cy", 1, "active", false, 401),
366 })));
367 assert_eq!(roster.hand_of("8:orgid:a"), Some(&RaisedHand { state_id: "s-1".into(), rank: 2 }));
368 assert_eq!(roster.hand_of("8:orgid:b").map(|hand| hand.rank), Some(1));
369 assert_eq!(roster.hand_of("8:orgid:c"), None);
370 let entries = roster.entries();
371 assert!(entries.iter().find(|entry| entry.display_name == "Bo").unwrap().hand.is_some());
372 }
373
374 #[test]
375 fn lowering_removes_the_key_and_the_hand() {
376 let mut roster = Roster::default();
377 roster.apply(&delta(json!({"8:orgid:a": with_hand(participant("Ana", 1, "active", false, 201), "s-1", 1)})));
378 assert!(roster.apply(&delta(json!({"8:orgid:a": participant("Ana", 2, "active", false, 201)}))));
379 assert_eq!(roster.hand_of("8:orgid:a"), None);
380 }
381
382 #[test]
383 fn endpoint_level_published_states_count_too() {
384 let mut roster = Roster::default();
385 let mut person = participant("Ana", 1, "active", false, 201);
386 person["endpoints"]["ep"]["publishedStates"] = json!([{"stateType": "raiseHands", "stateId": 7, "typeRank": 3}]);
387 roster.apply(&delta(json!({"8:orgid:a": person})));
388 assert_eq!(roster.hand_of("8:orgid:a"), Some(&RaisedHand { state_id: "7".into(), rank: 3 }));
389 }
390
321 #[test]
391 #[test]
322 fn missing_name_keeps_the_known_one() {
392 fn missing_name_keeps_the_known_one() {
323 let mut roster = Roster::default();
393 let mut roster = Roster::default();
crates/calling/src/share_audio.rs added +206 −0
@@ -0,0 +1,206 @@
1 use std::sync::Arc;
2 use std::sync::atomic::{AtomicBool, Ordering};
3 use std::time::{Duration, Instant};
4
5 use futures_util::StreamExt;
6 use libwebrtc::audio_source::native::NativeAudioSource;
7 use libwebrtc::native::apm::AudioProcessingModule;
8 use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
9 use libwebrtc::audio_stream::native::NativeAudioStream;
10 use libwebrtc::prelude::*;
11 use tokio::task::JoinHandle;
12
13 use crate::audio::{FRAME_SAMPLES, SAMPLE_RATE, SineGenerator};
14 use crate::audio_io::AudioMode;
15 use crate::capture::Capture;
16 use crate::devices::DeviceChoice;
17 use crate::error::{Error, Result};
18 use crate::mixer::mix_frames;
19 use crate::pcm::SampleQueue;
20 use crate::sound_capture::{LoopbackKind, start_loopback, start_microphone};
21
22 const SOURCE_QUEUE_MS: u32 = 100;
23 const FRAME_PERIOD: Duration = Duration::from_millis(10);
24 const MAX_LAG: Duration = Duration::from_millis(100);
25 const SYSTEM_TONE_HZ: f32 = 660.0;
26 const SYNTHETIC_AMPLITUDE: f32 = 0.3;
27
28 enum FrameSource {
29 Captured(SampleQueue),
30 Tone(SineGenerator),
31 Silence,
32 }
33
34 impl FrameSource {
35 fn next_frame(&mut self) -> Vec<i16> {
36 match self {
37 FrameSource::Captured(queue) => queue.next_frame().0,
38 FrameSource::Tone(generator) => generator.next_frame(),
39 FrameSource::Silence => vec![0; FRAME_SAMPLES],
40 }
41 }
42 }
43
44 struct Feeder {
45 source: NativeAudioSource,
46 microphone: FrameSource,
47 computer: FrameSource,
48 far_end: SampleQueue,
49 microphone_muted: Arc<AtomicBool>,
50 running: Arc<AtomicBool>,
51 runtime: tokio::runtime::Handle,
52 }
53
54 impl Feeder {
55 fn run(mut self) {
56 let mut processing = AudioProcessingModule::new(true, false, true, true);
57 let mut due = Instant::now();
58 while self.running.load(Ordering::SeqCst) {
59 due += FRAME_PERIOD;
60 let now = Instant::now();
61 if due > now {
62 std::thread::sleep(due - now);
63 } else if now - due > MAX_LAG {
64 due = now;
65 }
66 let (mut far_end, has_far_end) = self.far_end.next_frame();
67 if has_far_end {
68 let _ = processing.process_reverse_stream(&mut far_end, SAMPLE_RATE as i32, 1);
69 }
70 let muted = self.microphone_muted.load(Ordering::SeqCst);
71 let mut microphone = self.microphone.next_frame();
72 if !muted {
73 let _ = processing.process_stream(&mut microphone, SAMPLE_RATE as i32, 1);
74 }
75 let computer = self.computer.next_frame();
76 let frame = AudioFrame {
77 data: mix_frames(&microphone, &computer, muted).into(),
78 sample_rate: SAMPLE_RATE,
79 num_channels: 1,
80 samples_per_channel: FRAME_SAMPLES as u32,
81 };
82 if self.runtime.block_on(self.source.capture_frame(&frame)).is_err() {
83 break;
84 }
85 }
86 }
87 }
88
89 /// Mic plus computer sound mixed into one track that replaces the device track while sharing.
90 pub struct ShareAudio {
91 pub track: RtcAudioTrack,
92 pub loopback: LoopbackKind,
93 pub warning: Option<String>,
94 microphone_muted: Arc<AtomicBool>,
95 running: Arc<AtomicBool>,
96 feeder: Option<std::thread::JoinHandle<()>>,
97 far_end_task: Option<JoinHandle<()>>,
98 _captures: Vec<Capture>,
99 }
100
101 impl ShareAudio {
102 pub fn start(
103 factory: &PeerConnectionFactory,
104 mode: AudioMode,
105 tone_hz: f32,
106 input: &DeviceChoice,
107 microphone_muted: bool,
108 remote: Option<RtcAudioTrack>,
109 ) -> Result<Self> {
110 let mut captures = Vec::new();
111 let mut warning = None;
112 let (microphone, computer, loopback) = if mode == AudioMode::Platform {
113 let computer_queue = SampleQueue::default();
114 let started = start_loopback(computer_queue.clone())?;
115 captures.push(started.capture);
116 warning = started.warning;
117 let microphone_queue = SampleQueue::default();
118 let microphone = match start_microphone(input, microphone_queue.clone()) {
119 Ok(capture) => {
120 captures.push(capture);
121 FrameSource::Captured(microphone_queue)
122 }
123 Err(error) => {
124 warning.get_or_insert(format!("microphone not captured while sharing sound: {error}"));
125 FrameSource::Silence
126 }
127 };
128 (microphone, FrameSource::Captured(computer_queue), started.kind)
129 } else {
130 let microphone = if mode == AudioMode::Tone {
131 FrameSource::Tone(SineGenerator::new(tone_hz, SYNTHETIC_AMPLITUDE))
132 } else {
133 FrameSource::Silence
134 };
135 (microphone, FrameSource::Tone(SineGenerator::new(SYSTEM_TONE_HZ, SYNTHETIC_AMPLITUDE)), LoopbackKind::Synthetic)
136 };
137 let source = NativeAudioSource::new(AudioSourceOptions::default(), SAMPLE_RATE, 1, SOURCE_QUEUE_MS);
138 let track = factory.create_audio_track("microphone", source.clone());
139 let far_end = SampleQueue::default();
140 let far_end_task = remote.map(|remote| tokio::spawn(feed_far_end(remote, far_end.clone())));
141 let microphone_muted = Arc::new(AtomicBool::new(microphone_muted));
142 let running = Arc::new(AtomicBool::new(true));
143 let feeder = Feeder {
144 source,
145 microphone,
146 computer,
147 far_end,
148 microphone_muted: microphone_muted.clone(),
149 running: running.clone(),
150 runtime: tokio::runtime::Handle::current(),
151 };
152 let thread = std::thread::Builder::new()
153 .name("share-audio".into())
154 .spawn(move || feeder.run())
155 .map_err(|error| Error::Audio(format!("share audio thread: {error}")))?;
156 Ok(ShareAudio {
157 track,
158 loopback,
159 warning,
160 microphone_muted,
161 running,
162 feeder: Some(thread),
163 far_end_task,
164 _captures: captures,
165 })
166 }
167
168 pub fn set_microphone_muted(&self, muted: bool) {
169 self.microphone_muted.store(muted, Ordering::SeqCst);
170 }
171 }
172
173 impl Drop for ShareAudio {
174 fn drop(&mut self) {
175 self.running.store(false, Ordering::SeqCst);
176 if let Some(task) = self.far_end_task.take() {
177 task.abort();
178 }
179 if let Some(thread) = self.feeder.take() {
180 let _ = thread.join();
181 }
182 }
183 }
184
185 async fn feed_far_end(remote: RtcAudioTrack, queue: SampleQueue) {
186 let mut stream = NativeAudioStream::new(remote, SAMPLE_RATE as i32, 1);
187 while let Some(frame) = stream.next().await {
188 queue.push(&frame.data);
189 }
190 }
191
192 #[cfg(test)]
193 mod tests {
194 use super::*;
195 use crate::devices::shared_factory;
196
197 #[tokio::test(flavor = "multi_thread")]
198 async fn synthetic_sources_start_and_stop_cleanly() {
199 let audio = ShareAudio::start(&shared_factory(), AudioMode::Tone, 440.0, &DeviceChoice::SystemDefault, true, None).unwrap();
200 assert_eq!(audio.loopback, LoopbackKind::Synthetic);
201 assert!(audio.warning.is_none());
202 audio.set_microphone_muted(false);
203 tokio::time::sleep(Duration::from_millis(60)).await;
204 drop(audio);
205 }
206 }
@@ -0,0 +1,206 @@
1use std::sync::Arc;
2use std::sync::atomic::{AtomicBool, Ordering};
3use std::time::{Duration, Instant};
4
5use futures_util::StreamExt;
6use libwebrtc::audio_source::native::NativeAudioSource;
7use libwebrtc::native::apm::AudioProcessingModule;
8use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
9use libwebrtc::audio_stream::native::NativeAudioStream;
10use libwebrtc::prelude::*;
11use tokio::task::JoinHandle;
12
13use crate::audio::{FRAME_SAMPLES, SAMPLE_RATE, SineGenerator};
14use crate::audio_io::AudioMode;
15use crate::capture::Capture;
16use crate::devices::DeviceChoice;
17use crate::error::{Error, Result};
18use crate::mixer::mix_frames;
19use crate::pcm::SampleQueue;
20use crate::sound_capture::{LoopbackKind, start_loopback, start_microphone};
21
22const SOURCE_QUEUE_MS: u32 = 100;
23const FRAME_PERIOD: Duration = Duration::from_millis(10);
24const MAX_LAG: Duration = Duration::from_millis(100);
25const SYSTEM_TONE_HZ: f32 = 660.0;
26const SYNTHETIC_AMPLITUDE: f32 = 0.3;
27
28enum FrameSource {
29 Captured(SampleQueue),
30 Tone(SineGenerator),
31 Silence,
32}
33
34impl FrameSource {
35 fn next_frame(&mut self) -> Vec<i16> {
36 match self {
37 FrameSource::Captured(queue) => queue.next_frame().0,
38 FrameSource::Tone(generator) => generator.next_frame(),
39 FrameSource::Silence => vec![0; FRAME_SAMPLES],
40 }
41 }
42}
43
44struct Feeder {
45 source: NativeAudioSource,
46 microphone: FrameSource,
47 computer: FrameSource,
48 far_end: SampleQueue,
49 microphone_muted: Arc<AtomicBool>,
50 running: Arc<AtomicBool>,
51 runtime: tokio::runtime::Handle,
52}
53
54impl Feeder {
55 fn run(mut self) {
56 let mut processing = AudioProcessingModule::new(true, false, true, true);
57 let mut due = Instant::now();
58 while self.running.load(Ordering::SeqCst) {
59 due += FRAME_PERIOD;
60 let now = Instant::now();
61 if due > now {
62 std::thread::sleep(due - now);
63 } else if now - due > MAX_LAG {
64 due = now;
65 }
66 let (mut far_end, has_far_end) = self.far_end.next_frame();
67 if has_far_end {
68 let _ = processing.process_reverse_stream(&mut far_end, SAMPLE_RATE as i32, 1);
69 }
70 let muted = self.microphone_muted.load(Ordering::SeqCst);
71 let mut microphone = self.microphone.next_frame();
72 if !muted {
73 let _ = processing.process_stream(&mut microphone, SAMPLE_RATE as i32, 1);
74 }
75 let computer = self.computer.next_frame();
76 let frame = AudioFrame {
77 data: mix_frames(&microphone, &computer, muted).into(),
78 sample_rate: SAMPLE_RATE,
79 num_channels: 1,
80 samples_per_channel: FRAME_SAMPLES as u32,
81 };
82 if self.runtime.block_on(self.source.capture_frame(&frame)).is_err() {
83 break;
84 }
85 }
86 }
87}
88
89/// Mic plus computer sound mixed into one track that replaces the device track while sharing.
90pub struct ShareAudio {
91 pub track: RtcAudioTrack,
92 pub loopback: LoopbackKind,
93 pub warning: Option<String>,
94 microphone_muted: Arc<AtomicBool>,
95 running: Arc<AtomicBool>,
96 feeder: Option<std::thread::JoinHandle<()>>,
97 far_end_task: Option<JoinHandle<()>>,
98 _captures: Vec<Capture>,
99}
100
101impl ShareAudio {
102 pub fn start(
103 factory: &PeerConnectionFactory,
104 mode: AudioMode,
105 tone_hz: f32,
106 input: &DeviceChoice,
107 microphone_muted: bool,
108 remote: Option<RtcAudioTrack>,
109 ) -> Result<Self> {
110 let mut captures = Vec::new();
111 let mut warning = None;
112 let (microphone, computer, loopback) = if mode == AudioMode::Platform {
113 let computer_queue = SampleQueue::default();
114 let started = start_loopback(computer_queue.clone())?;
115 captures.push(started.capture);
116 warning = started.warning;
117 let microphone_queue = SampleQueue::default();
118 let microphone = match start_microphone(input, microphone_queue.clone()) {
119 Ok(capture) => {
120 captures.push(capture);
121 FrameSource::Captured(microphone_queue)
122 }
123 Err(error) => {
124 warning.get_or_insert(format!("microphone not captured while sharing sound: {error}"));
125 FrameSource::Silence
126 }
127 };
128 (microphone, FrameSource::Captured(computer_queue), started.kind)
129 } else {
130 let microphone = if mode == AudioMode::Tone {
131 FrameSource::Tone(SineGenerator::new(tone_hz, SYNTHETIC_AMPLITUDE))
132 } else {
133 FrameSource::Silence
134 };
135 (microphone, FrameSource::Tone(SineGenerator::new(SYSTEM_TONE_HZ, SYNTHETIC_AMPLITUDE)), LoopbackKind::Synthetic)
136 };
137 let source = NativeAudioSource::new(AudioSourceOptions::default(), SAMPLE_RATE, 1, SOURCE_QUEUE_MS);
138 let track = factory.create_audio_track("microphone", source.clone());
139 let far_end = SampleQueue::default();
140 let far_end_task = remote.map(|remote| tokio::spawn(feed_far_end(remote, far_end.clone())));
141 let microphone_muted = Arc::new(AtomicBool::new(microphone_muted));
142 let running = Arc::new(AtomicBool::new(true));
143 let feeder = Feeder {
144 source,
145 microphone,
146 computer,
147 far_end,
148 microphone_muted: microphone_muted.clone(),
149 running: running.clone(),
150 runtime: tokio::runtime::Handle::current(),
151 };
152 let thread = std::thread::Builder::new()
153 .name("share-audio".into())
154 .spawn(move || feeder.run())
155 .map_err(|error| Error::Audio(format!("share audio thread: {error}")))?;
156 Ok(ShareAudio {
157 track,
158 loopback,
159 warning,
160 microphone_muted,
161 running,
162 feeder: Some(thread),
163 far_end_task,
164 _captures: captures,
165 })
166 }
167
168 pub fn set_microphone_muted(&self, muted: bool) {
169 self.microphone_muted.store(muted, Ordering::SeqCst);
170 }
171}
172
173impl Drop for ShareAudio {
174 fn drop(&mut self) {
175 self.running.store(false, Ordering::SeqCst);
176 if let Some(task) = self.far_end_task.take() {
177 task.abort();
178 }
179 if let Some(thread) = self.feeder.take() {
180 let _ = thread.join();
181 }
182 }
183}
184
185async fn feed_far_end(remote: RtcAudioTrack, queue: SampleQueue) {
186 let mut stream = NativeAudioStream::new(remote, SAMPLE_RATE as i32, 1);
187 while let Some(frame) = stream.next().await {
188 queue.push(&frame.data);
189 }
190}
191
192#[cfg(test)]
193mod tests {
194 use super::*;
195 use crate::devices::shared_factory;
196
197 #[tokio::test(flavor = "multi_thread")]
198 async fn synthetic_sources_start_and_stop_cleanly() {
199 let audio = ShareAudio::start(&shared_factory(), AudioMode::Tone, 440.0, &DeviceChoice::SystemDefault, true, None).unwrap();
200 assert_eq!(audio.loopback, LoopbackKind::Synthetic);
201 assert!(audio.warning.is_none());
202 audio.set_microphone_muted(false);
203 tokio::time::sleep(Duration::from_millis(60)).await;
204 drop(audio);
205 }
206}
crates/calling/src/signaling.rs +77 −1
@@ -4,6 +4,7 @@ use serde_json::{Map, Value, json};
4 4 use session::{ApiResponse, GRAPH, Method, Request, Scope, Session};
5 5
6 6 use crate::error::{Error, Result};
7 use crate::reaction::{DEFAULT_SKIN_TONE, Reaction, reaction_message};
7 8 use crate::relay::ic3_scope;
8 9 use crate::timeline::Timeline;
9 10 use crate::trouter_events::{CallbackLinks, acceptance_links};
@@ -42,6 +43,7 @@ const SUBSCRIBE_LINK_NAMES: [&str; 6] = [
42 43 const CALL_LINK_NAMES: [&str; 5] = ["progress", "mediaAnswer", "acceptance", "redirection", "end"];
43 44 const AUDIO_MODALITIES: [&str; 1] = ["Audio"];
44 45 const MEETING_MESSAGE_ID: &str = "0";
46 const RAISE_HANDS: &str = "raiseHands";
45 47 const CANCEL_CODE: i64 = 487;
46 48 const DECLINE_CODE: i64 = 603;
47 49
@@ -108,6 +110,7 @@ impl Default for TenantRouting {
108 110 pub struct Conversation {
109 111 pub controller: String,
110 112 pub links: BTreeMap<String, String>,
113 pub chat_thread: Option<String>,
111 114 }
112 115
113 116 impl Conversation {
@@ -173,6 +176,7 @@ pub struct Signaling {
173 176 routing: TenantRouting,
174 177 timeline: Timeline,
175 178 endpoint_state_sequence: std::sync::atomic::AtomicU32,
179 state_sequence: std::sync::atomic::AtomicU32,
176 180 }
177 181
178 182 pub struct Invitation<'a> {
@@ -217,6 +221,7 @@ impl Signaling {
217 221 routing,
218 222 timeline,
219 223 endpoint_state_sequence: std::sync::atomic::AtomicU32::new(2),
224 state_sequence: std::sync::atomic::AtomicU32::new(0),
220 225 }
221 226 }
222 227
@@ -291,6 +296,7 @@ impl Signaling {
291 296 Ok(Conversation {
292 297 controller: subscribed.controller.clone(),
293 298 links,
299 chat_thread: subscribed.chat_thread.clone(),
294 300 })
295 301 }
296 302
@@ -311,6 +317,31 @@ impl Signaling {
311 317 self.post_json("POST updateEndpointState", url, body).await
312 318 }
313 319
320 fn next_state_sequence(&self) -> u32 {
321 self.state_sequence.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + 1
322 }
323
324 pub async fn raise_hand(&self, conversation: &Conversation, from: &Participant) -> Result<Option<String>> {
325 let body = raise_hand_body(from.wire(), self.next_state_sequence());
326 let response = self.send("POST publishState", Method::Post, conversation.link("publishState")?, Some(body)).await?;
327 Ok(response.body["publishStateResponse"]["stateId"].as_str().map(str::to_owned))
328 }
329
330 pub async fn lower_hands(&self, conversation: &Conversation, from: &Participant, state_ids: &[String]) -> Result<()> {
331 let body = remove_states_body(from.wire(), self.next_state_sequence(), state_ids);
332 self.post_json("POST removeState", conversation.link("removeState")?, body).await
333 }
334
335 pub async fn lower_all_hands(&self, conversation: &Conversation, from: &Participant) -> Result<()> {
336 let body = remove_all_hands_body(from.wire(), self.next_state_sequence());
337 self.post_json("POST removeState", conversation.link("removeState")?, body).await
338 }
339
340 pub async fn send_reaction(&self, conversation: &Conversation, from: &Participant, reaction: Reaction) -> Result<()> {
341 let body = reaction_message(from.wire(), reaction, &uuid::Uuid::new_v4().to_string(), &uuid::Uuid::new_v4().to_string());
342 self.post_json("POST sendMessage", conversation.link("sendMessage")?, body).await
343 }
344
314 345 pub async fn update_media_descriptions(&self, url: &str, descriptions: &[MediaDescription], request_id: u32) -> Result<()> {
315 346 let body = json!({
316 347 "UpdateMediaDescriptions": {
@@ -683,7 +714,31 @@ fn conversation_from(body: &Value) -> Result<Conversation> {
683 714 .collect()
684 715 })
685 716 .unwrap_or_default();
686 Ok(Conversation { controller, links })
717 Ok(Conversation { controller, links, chat_thread: chat_thread_id(body) })
718 }
719
720 pub fn raise_hand_body(from: Value, sequence_number: u32) -> Value {
721 json!({
722 "from": from,
723 "publishedState": {
724 "stateType": RAISE_HANDS,
725 "level": "user",
726 "content": {"skinTone": DEFAULT_SKIN_TONE},
727 "sequenceNumber": sequence_number,
728 },
729 })
730 }
731
732 pub fn remove_states_body(from: Value, sequence_number: u32, state_ids: &[String]) -> Value {
733 json!({"from": from, "sequenceNumber": sequence_number, "scope": "specified", "stateIds": state_ids})
734 }
735
736 pub fn remove_all_hands_body(from: Value, sequence_number: u32) -> Value {
737 json!({"from": from, "sequenceNumber": sequence_number, "scope": "all", "stateType": RAISE_HANDS})
738 }
739
740 pub fn chat_thread_id(body: &Value) -> Option<String> {
741 body["activeModalities"]["groupChat"]["threadId"].as_str().map(str::to_owned)
687 742 }
688 743
689 744 fn attached_from(body: &Value) -> Result<Attached> {
@@ -760,6 +815,27 @@ pub async fn find_echo_bot_thread(session: &Session, self_object_id: &str) -> Re
760 815 mod tests {
761 816 use super::*;
762 817
818 #[test]
819 fn raising_publishes_a_raise_hands_state_and_lowering_names_the_state() {
820 let raised = raise_hand_body(json!({"id": "8:orgid:me"}), 4);
821 assert_eq!(raised["publishedState"]["stateType"], "raiseHands");
822 assert_eq!(raised["publishedState"]["level"], "user");
823 assert_eq!(raised["publishedState"]["sequenceNumber"], 4);
824 let lowered = remove_states_body(json!({"id": "8:orgid:me"}), 5, &["s-1".to_owned()]);
825 assert_eq!(lowered["scope"], "specified");
826 assert_eq!(lowered["stateIds"][0], "s-1");
827 let all = remove_all_hands_body(json!({"id": "8:orgid:me"}), 6);
828 assert_eq!(all["scope"], "all");
829 assert_eq!(all["stateType"], "raiseHands");
830 }
831
832 #[test]
833 fn the_meeting_chat_thread_comes_from_the_group_chat_modality() {
834 let body = json!({"activeModalities": {"groupChat": {"threadId": "19:meeting_abc@thread.v2"}}});
835 assert_eq!(chat_thread_id(&body).as_deref(), Some("19:meeting_abc@thread.v2"));
836 assert_eq!(chat_thread_id(&json!({"activeModalities": {}})), None);
837 }
838
763 839 fn from() -> Participant {
764 840 Participant {
765 841 mri: "8:orgid:00000000-0000-0000-0000-000000000001".into(),
@@ -4,6 +4,7 @@ use serde_json::{Map, Value, json};
4use session::{ApiResponse, GRAPH, Method, Request, Scope, Session};
4use session::{ApiResponse, GRAPH, Method, Request, Scope, Session};
5
5
6use crate::error::{Error, Result};
6use crate::error::{Error, Result};
7use crate::reaction::{DEFAULT_SKIN_TONE, Reaction, reaction_message};
7use crate::relay::ic3_scope;
8use crate::relay::ic3_scope;
8use crate::timeline::Timeline;
9use crate::timeline::Timeline;
9use crate::trouter_events::{CallbackLinks, acceptance_links};
10use crate::trouter_events::{CallbackLinks, acceptance_links};
@@ -42,6 +43,7 @@ const SUBSCRIBE_LINK_NAMES: [&str; 6] = [
42const CALL_LINK_NAMES: [&str; 5] = ["progress", "mediaAnswer", "acceptance", "redirection", "end"];
43const CALL_LINK_NAMES: [&str; 5] = ["progress", "mediaAnswer", "acceptance", "redirection", "end"];
43const AUDIO_MODALITIES: [&str; 1] = ["Audio"];
44const AUDIO_MODALITIES: [&str; 1] = ["Audio"];
44const MEETING_MESSAGE_ID: &str = "0";
45const MEETING_MESSAGE_ID: &str = "0";
46const RAISE_HANDS: &str = "raiseHands";
45const CANCEL_CODE: i64 = 487;
47const CANCEL_CODE: i64 = 487;
46const DECLINE_CODE: i64 = 603;
48const DECLINE_CODE: i64 = 603;
47
49
@@ -108,6 +110,7 @@ impl Default for TenantRouting {
108pub struct Conversation {
110pub struct Conversation {
109 pub controller: String,
111 pub controller: String,
110 pub links: BTreeMap<String, String>,
112 pub links: BTreeMap<String, String>,
113 pub chat_thread: Option<String>,
111}
114}
112
115
113impl Conversation {
116impl Conversation {
@@ -173,6 +176,7 @@ pub struct Signaling {
173 routing: TenantRouting,
176 routing: TenantRouting,
174 timeline: Timeline,
177 timeline: Timeline,
175 endpoint_state_sequence: std::sync::atomic::AtomicU32,
178 endpoint_state_sequence: std::sync::atomic::AtomicU32,
179 state_sequence: std::sync::atomic::AtomicU32,
176}
180}
177
181
178pub struct Invitation<'a> {
182pub struct Invitation<'a> {
@@ -217,6 +221,7 @@ impl Signaling {
217 routing,
221 routing,
218 timeline,
222 timeline,
219 endpoint_state_sequence: std::sync::atomic::AtomicU32::new(2),
223 endpoint_state_sequence: std::sync::atomic::AtomicU32::new(2),
224 state_sequence: std::sync::atomic::AtomicU32::new(0),
220 }
225 }
221 }
226 }
222
227
@@ -291,6 +296,7 @@ impl Signaling {
291 Ok(Conversation {
296 Ok(Conversation {
292 controller: subscribed.controller.clone(),
297 controller: subscribed.controller.clone(),
293 links,
298 links,
299 chat_thread: subscribed.chat_thread.clone(),
294 })
300 })
295 }
301 }
296
302
@@ -311,6 +317,31 @@ impl Signaling {
311 self.post_json("POST updateEndpointState", url, body).await
317 self.post_json("POST updateEndpointState", url, body).await
312 }
318 }
313
319
320 fn next_state_sequence(&self) -> u32 {
321 self.state_sequence.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + 1
322 }
323
324 pub async fn raise_hand(&self, conversation: &Conversation, from: &Participant) -> Result<Option<String>> {
325 let body = raise_hand_body(from.wire(), self.next_state_sequence());
326 let response = self.send("POST publishState", Method::Post, conversation.link("publishState")?, Some(body)).await?;
327 Ok(response.body["publishStateResponse"]["stateId"].as_str().map(str::to_owned))
328 }
329
330 pub async fn lower_hands(&self, conversation: &Conversation, from: &Participant, state_ids: &[String]) -> Result<()> {
331 let body = remove_states_body(from.wire(), self.next_state_sequence(), state_ids);
332 self.post_json("POST removeState", conversation.link("removeState")?, body).await
333 }
334
335 pub async fn lower_all_hands(&self, conversation: &Conversation, from: &Participant) -> Result<()> {
336 let body = remove_all_hands_body(from.wire(), self.next_state_sequence());
337 self.post_json("POST removeState", conversation.link("removeState")?, body).await
338 }
339
340 pub async fn send_reaction(&self, conversation: &Conversation, from: &Participant, reaction: Reaction) -> Result<()> {
341 let body = reaction_message(from.wire(), reaction, &uuid::Uuid::new_v4().to_string(), &uuid::Uuid::new_v4().to_string());
342 self.post_json("POST sendMessage", conversation.link("sendMessage")?, body).await
343 }
344
314 pub async fn update_media_descriptions(&self, url: &str, descriptions: &[MediaDescription], request_id: u32) -> Result<()> {
345 pub async fn update_media_descriptions(&self, url: &str, descriptions: &[MediaDescription], request_id: u32) -> Result<()> {
315 let body = json!({
346 let body = json!({
316 "UpdateMediaDescriptions": {
347 "UpdateMediaDescriptions": {
@@ -683,7 +714,31 @@ fn conversation_from(body: &Value) -> Result<Conversation> {
683 .collect()
714 .collect()
684 })
715 })
685 .unwrap_or_default();
716 .unwrap_or_default();
686 Ok(Conversation { controller, links })
717 Ok(Conversation { controller, links, chat_thread: chat_thread_id(body) })
718}
719
720pub fn raise_hand_body(from: Value, sequence_number: u32) -> Value {
721 json!({
722 "from": from,
723 "publishedState": {
724 "stateType": RAISE_HANDS,
725 "level": "user",
726 "content": {"skinTone": DEFAULT_SKIN_TONE},
727 "sequenceNumber": sequence_number,
728 },
729 })
730}
731
732pub fn remove_states_body(from: Value, sequence_number: u32, state_ids: &[String]) -> Value {
733 json!({"from": from, "sequenceNumber": sequence_number, "scope": "specified", "stateIds": state_ids})
734}
735
736pub fn remove_all_hands_body(from: Value, sequence_number: u32) -> Value {
737 json!({"from": from, "sequenceNumber": sequence_number, "scope": "all", "stateType": RAISE_HANDS})
738}
739
740pub fn chat_thread_id(body: &Value) -> Option<String> {
741 body["activeModalities"]["groupChat"]["threadId"].as_str().map(str::to_owned)
687}
742}
688
743
689fn attached_from(body: &Value) -> Result<Attached> {
744fn attached_from(body: &Value) -> Result<Attached> {
@@ -760,6 +815,27 @@ pub async fn find_echo_bot_thread(session: &Session, self_object_id: &str) -> Re
760mod tests {
815mod tests {
761 use super::*;
816 use super::*;
762
817
818 #[test]
819 fn raising_publishes_a_raise_hands_state_and_lowering_names_the_state() {
820 let raised = raise_hand_body(json!({"id": "8:orgid:me"}), 4);
821 assert_eq!(raised["publishedState"]["stateType"], "raiseHands");
822 assert_eq!(raised["publishedState"]["level"], "user");
823 assert_eq!(raised["publishedState"]["sequenceNumber"], 4);
824 let lowered = remove_states_body(json!({"id": "8:orgid:me"}), 5, &["s-1".to_owned()]);
825 assert_eq!(lowered["scope"], "specified");
826 assert_eq!(lowered["stateIds"][0], "s-1");
827 let all = remove_all_hands_body(json!({"id": "8:orgid:me"}), 6);
828 assert_eq!(all["scope"], "all");
829 assert_eq!(all["stateType"], "raiseHands");
830 }
831
832 #[test]
833 fn the_meeting_chat_thread_comes_from_the_group_chat_modality() {
834 let body = json!({"activeModalities": {"groupChat": {"threadId": "19:meeting_abc@thread.v2"}}});
835 assert_eq!(chat_thread_id(&body).as_deref(), Some("19:meeting_abc@thread.v2"));
836 assert_eq!(chat_thread_id(&json!({"activeModalities": {}})), None);
837 }
838
763 fn from() -> Participant {
839 fn from() -> Participant {
764 Participant {
840 Participant {
765 mri: "8:orgid:00000000-0000-0000-0000-000000000001".into(),
841 mri: "8:orgid:00000000-0000-0000-0000-000000000001".into(),
crates/calling/src/sound_capture.rs added +168 −0
@@ -0,0 +1,168 @@
1 use std::sync::mpsc;
2
3 use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
4 use cpal::{Device, SampleFormat, Stream, StreamConfig};
5
6 use crate::capture::Capture;
7 use crate::devices::DeviceChoice;
8 use crate::error::{Error, Result};
9 use crate::pcm::{MonoResampler, SampleQueue};
10
11 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
12 pub enum LoopbackKind {
13 ProcessExclude,
14 WholeEndpoint,
15 Monitor,
16 Synthetic,
17 }
18
19 impl LoopbackKind {
20 pub fn excludes_own_playback(self) -> bool {
21 matches!(self, LoopbackKind::ProcessExclude | LoopbackKind::Synthetic)
22 }
23 }
24
25 pub struct LoopbackStart {
26 pub capture: Capture,
27 pub kind: LoopbackKind,
28 pub warning: Option<String>,
29 }
30
31 fn audio_error(what: &str, error: impl std::fmt::Display) -> Error {
32 Error::Audio(format!("{what}: {error}"))
33 }
34
35 fn named_input(choice: &DeviceChoice) -> Option<Device> {
36 let DeviceChoice::Device(wanted) = choice else { return None };
37 cpal::default_host()
38 .input_devices()
39 .ok()?
40 .find(|device| device.description().is_ok_and(|description| description.name() == wanted))
41 }
42
43 pub fn start_microphone(choice: &DeviceChoice, queue: SampleQueue) -> Result<Capture> {
44 let device = named_input(choice)
45 .or_else(|| cpal::default_host().default_input_device())
46 .ok_or_else(|| Error::Audio("no microphone".into()))?;
47 let config = device.default_input_config().map_err(|error| audio_error("microphone format", error))?;
48 start_cpal_input(device, config.sample_format(), config.config(), queue)
49 }
50
51 #[cfg(windows)]
52 pub fn start_loopback(queue: SampleQueue) -> Result<LoopbackStart> {
53 match crate::loopback_windows::start_process_loopback(queue.clone(), std::process::id()) {
54 Ok(capture) => Ok(LoopbackStart { capture, kind: LoopbackKind::ProcessExclude, warning: None }),
55 Err(error) => {
56 let capture = start_endpoint_loopback(queue)?;
57 Ok(LoopbackStart {
58 capture,
59 kind: LoopbackKind::WholeEndpoint,
60 warning: Some(format!("process loopback unavailable ({error}); capturing the whole endpoint, call audio may echo")),
61 })
62 }
63 }
64 }
65
66 #[cfg(windows)]
67 fn start_endpoint_loopback(queue: SampleQueue) -> Result<Capture> {
68 let device = cpal::default_host()
69 .default_output_device()
70 .ok_or_else(|| Error::Audio("no output device".into()))?;
71 let config = device.default_output_config().map_err(|error| audio_error("output format", error))?;
72 start_cpal_input(device, config.sample_format(), config.config(), queue)
73 }
74
75 #[cfg(not(windows))]
76 pub fn start_loopback(queue: SampleQueue) -> Result<LoopbackStart> {
77 Ok(LoopbackStart { capture: start_monitor(queue)?, kind: LoopbackKind::Monitor, warning: None })
78 }
79
80 #[cfg(not(windows))]
81 fn start_monitor(queue: SampleQueue) -> Result<Capture> {
82 use std::io::Read;
83 use std::process::{Command, Stdio};
84 use std::sync::{Arc, Mutex};
85
86 const READ_BYTES: usize = 960;
87 let mut child = Command::new("parec")
88 .args(["--device=@DEFAULT_MONITOR@", "--format=s16le", "--rate=48000", "--channels=1", "--latency-msec=10"])
89 .stdout(Stdio::piped())
90 .stderr(Stdio::null())
91 .spawn()
92 .map_err(|error| audio_error("parec", error))?;
93 let mut output = child.stdout.take().ok_or_else(|| Error::Audio("parec without output".into()))?;
94 let child = Arc::new(Mutex::new(child));
95 let watched = child.clone();
96 Capture::spawn_thread("sound-monitor", move |stop| {
97 let watcher = std::thread::spawn({
98 let stop = stop.clone();
99 move || {
100 while !stop.load(std::sync::atomic::Ordering::SeqCst) {
101 std::thread::sleep(std::time::Duration::from_millis(50));
102 }
103 let mut child = watched.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
104 let _ = child.kill();
105 let _ = child.wait();
106 }
107 });
108 let mut bytes = [0u8; READ_BYTES];
109 while output.read_exact(&mut bytes).is_ok() {
110 let samples: Vec<i16> = bytes.as_chunks::<2>().0.iter().map(|pair| i16::from_le_bytes(*pair)).collect();
111 queue.push(&samples);
112 }
113 let _ = watcher.join();
114 })
115 .map_err(|error| audio_error("monitor thread", error))
116 }
117
118 fn start_cpal_input(device: Device, format: SampleFormat, config: StreamConfig, queue: SampleQueue) -> Result<Capture> {
119 let (ready_sender, ready) = mpsc::channel::<Result<()>>();
120 let capture = Capture::spawn_thread("sound-input", move |stop| {
121 match build_stream(&device, format, &config, queue) {
122 Ok(stream) => {
123 let started = stream.play().map_err(|error| audio_error("start", error));
124 let _ = ready_sender.send(started);
125 while !stop.load(std::sync::atomic::Ordering::SeqCst) {
126 std::thread::sleep(std::time::Duration::from_millis(50));
127 }
128 }
129 Err(error) => {
130 let _ = ready_sender.send(Err(error));
131 }
132 }
133 })
134 .map_err(|error| audio_error("input thread", error))?;
135 ready.recv().map_err(|_| Error::Audio("input thread ended".into()))??;
136 Ok(capture)
137 }
138
139 fn build_stream(device: &Device, format: SampleFormat, config: &StreamConfig, queue: SampleQueue) -> Result<Stream> {
140 let channels = usize::from(config.channels);
141 let mut resampler = MonoResampler::new(config.sample_rate);
142 let mut converted = Vec::new();
143 let failed = |_error| {};
144 match format {
145 SampleFormat::F32 => device.build_input_stream(
146 config,
147 move |data: &[f32], _| {
148 converted.clear();
149 resampler.convert(data, channels, &mut converted);
150 queue.push(&converted);
151 },
152 failed,
153 None,
154 ),
155 SampleFormat::I16 => device.build_input_stream(
156 config,
157 move |data: &[i16], _| {
158 converted.clear();
159 resampler.convert(&crate::pcm::i16_to_f32(data), channels, &mut converted);
160 queue.push(&converted);
161 },
162 failed,
163 None,
164 ),
165 other => return Err(Error::Audio(format!("unsupported sample format {other:?}"))),
166 }
167 .map_err(|error| audio_error("open input", error))
168 }
@@ -0,0 +1,168 @@
1use std::sync::mpsc;
2
3use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
4use cpal::{Device, SampleFormat, Stream, StreamConfig};
5
6use crate::capture::Capture;
7use crate::devices::DeviceChoice;
8use crate::error::{Error, Result};
9use crate::pcm::{MonoResampler, SampleQueue};
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub enum LoopbackKind {
13 ProcessExclude,
14 WholeEndpoint,
15 Monitor,
16 Synthetic,
17}
18
19impl LoopbackKind {
20 pub fn excludes_own_playback(self) -> bool {
21 matches!(self, LoopbackKind::ProcessExclude | LoopbackKind::Synthetic)
22 }
23}
24
25pub struct LoopbackStart {
26 pub capture: Capture,
27 pub kind: LoopbackKind,
28 pub warning: Option<String>,
29}
30
31fn audio_error(what: &str, error: impl std::fmt::Display) -> Error {
32 Error::Audio(format!("{what}: {error}"))
33}
34
35fn named_input(choice: &DeviceChoice) -> Option<Device> {
36 let DeviceChoice::Device(wanted) = choice else { return None };
37 cpal::default_host()
38 .input_devices()
39 .ok()?
40 .find(|device| device.description().is_ok_and(|description| description.name() == wanted))
41}
42
43pub fn start_microphone(choice: &DeviceChoice, queue: SampleQueue) -> Result<Capture> {
44 let device = named_input(choice)
45 .or_else(|| cpal::default_host().default_input_device())
46 .ok_or_else(|| Error::Audio("no microphone".into()))?;
47 let config = device.default_input_config().map_err(|error| audio_error("microphone format", error))?;
48 start_cpal_input(device, config.sample_format(), config.config(), queue)
49}
50
51#[cfg(windows)]
52pub fn start_loopback(queue: SampleQueue) -> Result<LoopbackStart> {
53 match crate::loopback_windows::start_process_loopback(queue.clone(), std::process::id()) {
54 Ok(capture) => Ok(LoopbackStart { capture, kind: LoopbackKind::ProcessExclude, warning: None }),
55 Err(error) => {
56 let capture = start_endpoint_loopback(queue)?;
57 Ok(LoopbackStart {
58 capture,
59 kind: LoopbackKind::WholeEndpoint,
60 warning: Some(format!("process loopback unavailable ({error}); capturing the whole endpoint, call audio may echo")),
61 })
62 }
63 }
64}
65
66#[cfg(windows)]
67fn start_endpoint_loopback(queue: SampleQueue) -> Result<Capture> {
68 let device = cpal::default_host()
69 .default_output_device()
70 .ok_or_else(|| Error::Audio("no output device".into()))?;
71 let config = device.default_output_config().map_err(|error| audio_error("output format", error))?;
72 start_cpal_input(device, config.sample_format(), config.config(), queue)
73}
74
75#[cfg(not(windows))]
76pub fn start_loopback(queue: SampleQueue) -> Result<LoopbackStart> {
77 Ok(LoopbackStart { capture: start_monitor(queue)?, kind: LoopbackKind::Monitor, warning: None })
78}
79
80#[cfg(not(windows))]
81fn start_monitor(queue: SampleQueue) -> Result<Capture> {
82 use std::io::Read;
83 use std::process::{Command, Stdio};
84 use std::sync::{Arc, Mutex};
85
86 const READ_BYTES: usize = 960;
87 let mut child = Command::new("parec")
88 .args(["--device=@DEFAULT_MONITOR@", "--format=s16le", "--rate=48000", "--channels=1", "--latency-msec=10"])
89 .stdout(Stdio::piped())
90 .stderr(Stdio::null())
91 .spawn()
92 .map_err(|error| audio_error("parec", error))?;
93 let mut output = child.stdout.take().ok_or_else(|| Error::Audio("parec without output".into()))?;
94 let child = Arc::new(Mutex::new(child));
95 let watched = child.clone();
96 Capture::spawn_thread("sound-monitor", move |stop| {
97 let watcher = std::thread::spawn({
98 let stop = stop.clone();
99 move || {
100 while !stop.load(std::sync::atomic::Ordering::SeqCst) {
101 std::thread::sleep(std::time::Duration::from_millis(50));
102 }
103 let mut child = watched.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
104 let _ = child.kill();
105 let _ = child.wait();
106 }
107 });
108 let mut bytes = [0u8; READ_BYTES];
109 while output.read_exact(&mut bytes).is_ok() {
110 let samples: Vec<i16> = bytes.as_chunks::<2>().0.iter().map(|pair| i16::from_le_bytes(*pair)).collect();
111 queue.push(&samples);
112 }
113 let _ = watcher.join();
114 })
115 .map_err(|error| audio_error("monitor thread", error))
116}
117
118fn start_cpal_input(device: Device, format: SampleFormat, config: StreamConfig, queue: SampleQueue) -> Result<Capture> {
119 let (ready_sender, ready) = mpsc::channel::<Result<()>>();
120 let capture = Capture::spawn_thread("sound-input", move |stop| {
121 match build_stream(&device, format, &config, queue) {
122 Ok(stream) => {
123 let started = stream.play().map_err(|error| audio_error("start", error));
124 let _ = ready_sender.send(started);
125 while !stop.load(std::sync::atomic::Ordering::SeqCst) {
126 std::thread::sleep(std::time::Duration::from_millis(50));
127 }
128 }
129 Err(error) => {
130 let _ = ready_sender.send(Err(error));
131 }
132 }
133 })
134 .map_err(|error| audio_error("input thread", error))?;
135 ready.recv().map_err(|_| Error::Audio("input thread ended".into()))??;
136 Ok(capture)
137}
138
139fn build_stream(device: &Device, format: SampleFormat, config: &StreamConfig, queue: SampleQueue) -> Result<Stream> {
140 let channels = usize::from(config.channels);
141 let mut resampler = MonoResampler::new(config.sample_rate);
142 let mut converted = Vec::new();
143 let failed = |_error| {};
144 match format {
145 SampleFormat::F32 => device.build_input_stream(
146 config,
147 move |data: &[f32], _| {
148 converted.clear();
149 resampler.convert(data, channels, &mut converted);
150 queue.push(&converted);
151 },
152 failed,
153 None,
154 ),
155 SampleFormat::I16 => device.build_input_stream(
156 config,
157 move |data: &[i16], _| {
158 converted.clear();
159 resampler.convert(&crate::pcm::i16_to_f32(data), channels, &mut converted);
160 queue.push(&converted);
161 },
162 failed,
163 None,
164 ),
165 other => return Err(Error::Audio(format!("unsupported sample format {other:?}"))),
166 }
167 .map_err(|error| audio_error("open input", error))
168}
crates/calling/src/trouter_events.rs +4 −0
@@ -8,6 +8,7 @@ use serde_json::{Value, json};
8 8
9 9 use crate::end::{EndKind, classify_end};
10 10 use crate::error::{Error, Result};
11 use crate::reaction::{ReactionEvent, parse_reactions};
11 12
12 13 const CALLBACK_ROOT: &str = "callAgent/";
13 14 const GZIP_ENCODING: &str = "gzip";
@@ -114,6 +115,7 @@ pub enum CallEvent {
114 115 Speakers(Vec<u32>),
115 116 AddParticipantSuccess(Value),
116 117 AddParticipantFailure(Value),
118 Reactions(Vec<ReactionEvent>),
117 119 End(CallEnd),
118 120 Other { scope: String, event: String },
119 121 }
@@ -130,6 +132,7 @@ impl CallEvent {
130 132 CallEvent::Speakers(_) => "call/speakers".into(),
131 133 CallEvent::AddParticipantSuccess(_) => "conversation/addParticipantSuccess".into(),
132 134 CallEvent::AddParticipantFailure(_) => "conversation/addParticipantFailure".into(),
135 CallEvent::Reactions(_) => "conversation/receiveMessage".into(),
133 136 CallEvent::End(_) => "call/end".into(),
134 137 CallEvent::Other { scope, event } => format!("{scope}/{event}"),
135 138 }
@@ -143,6 +146,7 @@ pub fn classify(path: &str, body: Value) -> Result<(String, CallEvent)> {
143 146 ("conversation", "conversationUpdate") => CallEvent::ConversationUpdate(body),
144 147 ("conversation", "rosterUpdate") => CallEvent::RosterUpdate(body),
145 148 ("conversation", "addParticipantSuccess") => CallEvent::AddParticipantSuccess(body),
149 ("conversation", "receiveMessage") => CallEvent::Reactions(parse_reactions(&body)),
146 150 ("conversation", "addParticipantFailure") => CallEvent::AddParticipantFailure(body),
147 151 ("call", "acceptance") => CallEvent::Acceptance(acceptance(&body)?),
148 152 ("call", "progress") => CallEvent::Progress(progress(&body)),
@@ -8,6 +8,7 @@ use serde_json::{Value, json};
8
8
9use crate::end::{EndKind, classify_end};
9use crate::end::{EndKind, classify_end};
10use crate::error::{Error, Result};
10use crate::error::{Error, Result};
11use crate::reaction::{ReactionEvent, parse_reactions};
11
12
12const CALLBACK_ROOT: &str = "callAgent/";
13const CALLBACK_ROOT: &str = "callAgent/";
13const GZIP_ENCODING: &str = "gzip";
14const GZIP_ENCODING: &str = "gzip";
@@ -114,6 +115,7 @@ pub enum CallEvent {
114 Speakers(Vec<u32>),
115 Speakers(Vec<u32>),
115 AddParticipantSuccess(Value),
116 AddParticipantSuccess(Value),
116 AddParticipantFailure(Value),
117 AddParticipantFailure(Value),
118 Reactions(Vec<ReactionEvent>),
117 End(CallEnd),
119 End(CallEnd),
118 Other { scope: String, event: String },
120 Other { scope: String, event: String },
119}
121}
@@ -130,6 +132,7 @@ impl CallEvent {
130 CallEvent::Speakers(_) => "call/speakers".into(),
132 CallEvent::Speakers(_) => "call/speakers".into(),
131 CallEvent::AddParticipantSuccess(_) => "conversation/addParticipantSuccess".into(),
133 CallEvent::AddParticipantSuccess(_) => "conversation/addParticipantSuccess".into(),
132 CallEvent::AddParticipantFailure(_) => "conversation/addParticipantFailure".into(),
134 CallEvent::AddParticipantFailure(_) => "conversation/addParticipantFailure".into(),
135 CallEvent::Reactions(_) => "conversation/receiveMessage".into(),
133 CallEvent::End(_) => "call/end".into(),
136 CallEvent::End(_) => "call/end".into(),
134 CallEvent::Other { scope, event } => format!("{scope}/{event}"),
137 CallEvent::Other { scope, event } => format!("{scope}/{event}"),
135 }
138 }
@@ -143,6 +146,7 @@ pub fn classify(path: &str, body: Value) -> Result<(String, CallEvent)> {
143 ("conversation", "conversationUpdate") => CallEvent::ConversationUpdate(body),
146 ("conversation", "conversationUpdate") => CallEvent::ConversationUpdate(body),
144 ("conversation", "rosterUpdate") => CallEvent::RosterUpdate(body),
147 ("conversation", "rosterUpdate") => CallEvent::RosterUpdate(body),
145 ("conversation", "addParticipantSuccess") => CallEvent::AddParticipantSuccess(body),
148 ("conversation", "addParticipantSuccess") => CallEvent::AddParticipantSuccess(body),
149 ("conversation", "receiveMessage") => CallEvent::Reactions(parse_reactions(&body)),
146 ("conversation", "addParticipantFailure") => CallEvent::AddParticipantFailure(body),
150 ("conversation", "addParticipantFailure") => CallEvent::AddParticipantFailure(body),
147 ("call", "acceptance") => CallEvent::Acceptance(acceptance(&body)?),
151 ("call", "acceptance") => CallEvent::Acceptance(acceptance(&body)?),
148 ("call", "progress") => CallEvent::Progress(progress(&body)),
152 ("call", "progress") => CallEvent::Progress(progress(&body)),