Skip to main content

matrix_sdk_base/room/
call.rs

1// Copyright 2025 The Matrix.org Foundation C.I.C.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use ruma::{OwnedUserId, events::rtc::notification::CallIntent};
16
17use super::Room;
18
19/// Represents the consensus state of call intent among room members.
20/// Call members can advertise their intent to use audio or video, clients can
21/// use this in the UI and also to decide to start camera or not when joining.
22///
23/// This enum distinguishes between full consensus (all members advertise and
24/// agree), partial consensus (only some members advertise, but those who do
25/// agree), and no consensus (either no one advertises or advertisers disagree).
26#[derive(Debug, Clone, PartialEq, Eq)]
27pub enum CallIntentConsensus {
28    /// All members advertise and agree
29    Full(CallIntent),
30    /// Some members advertise and agree
31    Partial {
32        /// The call intent that advertising members agree on.
33        intent: CallIntent,
34        /// Number of members advertising and agreeing on this intent.
35        agreeing_count: u64,
36        /// Total number of members in the call.
37        total_count: u64,
38    },
39    /// No consensus. No one advertises or advertisers disagree.
40    None,
41}
42
43impl Room {
44    /// Is there a non expired membership with application `m.call` and scope
45    /// `m.room` in this room.
46    pub fn has_active_room_call(&self) -> bool {
47        self.info.read().has_active_room_call()
48    }
49
50    /// Returns a `Vec` of `OwnedUserId`'s that participate in the room call.
51    ///
52    /// MatrixRTC memberships with application `m.call` and scope `m.room` are
53    /// considered. A user can occur twice if they join with two devices.
54    /// Convert to a set depending if the different users are required or the
55    /// amount of sessions.
56    ///
57    /// The vector is ordered by oldest membership user to newest.
58    pub fn active_room_call_participants(&self) -> Vec<OwnedUserId> {
59        self.info.read().active_room_call_participants()
60    }
61
62    /// See [`RoomInfo::is_device_in_active_room_call`].
63    ///
64    /// [`RoomInfo::is_device_in_active_room_call`]: crate::RoomInfo::is_device_in_active_room_call
65    pub fn is_device_in_active_room_call(
66        &self,
67        user_id: &ruma::UserId,
68        device_id: &ruma::DeviceId,
69    ) -> bool {
70        self.info.read().is_device_in_active_room_call(user_id, device_id)
71    }
72
73    /// Get the consensus call intent for the current call, based on what
74    /// members are advertising.
75    pub fn active_room_call_consensus_intent(&self) -> CallIntentConsensus {
76        self.info.read().active_room_call_consensus_intent()
77    }
78}
79
80#[cfg(test)]
81mod tests {
82    use std::{ops::Sub, sync::Arc, time::Duration};
83
84    use assign::assign;
85    use matrix_sdk_test::{ALICE, BOB, CAROL, event_factory::EventFactory};
86    use ruma::{
87        DeviceId, EventId, MilliSecondsSinceUnixEpoch, OwnedUserId, UserId, device_id, event_id,
88        events::{
89            AnySyncStateEvent,
90            call::member::{
91                ActiveFocus, ActiveLivekitFocus, Application, CallApplicationContent,
92                CallMemberEventContent, CallMemberStateKey, Focus, LegacyMembershipData,
93                LegacyMembershipDataInit, LivekitFocus,
94            },
95            rtc::notification::CallIntent,
96        },
97        room_id,
98        serde::Raw,
99        time::SystemTime,
100        user_id,
101    };
102    use similar_asserts::assert_eq;
103
104    use super::{
105        super::{Room, RoomState},
106        CallIntentConsensus,
107    };
108    use crate::{
109        store::{MemoryStore, SaveLockedStateStore},
110        utils::RawStateEventWithKeys,
111    };
112
113    fn make_room_test_helper(room_type: RoomState) -> (Arc<MemoryStore>, Room) {
114        let store = Arc::new(MemoryStore::new());
115        let user_id = user_id!("@me:example.org");
116        let room_id = room_id!("!test:localhost");
117        let (sender, _receiver) = tokio::sync::broadcast::channel(1);
118
119        (
120            store.clone(),
121            Room::new(user_id, SaveLockedStateStore::new(store), room_id, room_type, sender),
122        )
123    }
124
125    fn timestamp(minutes_ago: u32) -> MilliSecondsSinceUnixEpoch {
126        MilliSecondsSinceUnixEpoch::from_system_time(
127            SystemTime::now().sub(Duration::from_secs((60 * minutes_ago).into())),
128        )
129        .expect("date out of range")
130    }
131
132    fn legacy_membership_for_my_call(
133        device_id: &DeviceId,
134        membership_id: &str,
135        minutes_ago: u32,
136    ) -> LegacyMembershipData {
137        let (application, foci) = foci_and_application();
138        assign!(
139            LegacyMembershipData::from(LegacyMembershipDataInit {
140                application,
141                device_id: device_id.to_owned(),
142                expires: Duration::from_millis(3_600_000),
143                foci_active: foci,
144                membership_id: membership_id.to_owned(),
145            }),
146            { created_ts: Some(timestamp(minutes_ago)) }
147        )
148    }
149
150    fn legacy_member_state_event(
151        memberships: Vec<LegacyMembershipData>,
152        ev_id: &EventId,
153        user_id: &UserId,
154    ) -> Raw<AnySyncStateEvent> {
155        let content = CallMemberEventContent::new_legacy(memberships);
156        EventFactory::new()
157            .sender(user_id)
158            .event(content)
159            .state_key(CallMemberStateKey::new(user_id.to_owned(), None, false).as_ref())
160            .event_id(ev_id)
161            // we can simply use now here since this will be dropped when using a MinimalStateEvent
162            // in the roomInfo
163            .server_ts(timestamp(0))
164            .into()
165    }
166
167    struct InitData<'a> {
168        device_id: &'a DeviceId,
169        minutes_ago: u32,
170    }
171
172    fn session_member_state_event(
173        ev_id: &EventId,
174        user_id: &UserId,
175        init_data: Option<InitData<'_>>,
176    ) -> Raw<AnySyncStateEvent> {
177        session_member_state_event_with_intent(ev_id, user_id, init_data, None)
178    }
179
180    fn session_member_state_event_with_intent(
181        ev_id: &EventId,
182        user_id: &UserId,
183        init_data: Option<InitData<'_>>,
184        call_intent: Option<CallIntent>,
185    ) -> Raw<AnySyncStateEvent> {
186        let mut app_content = CallApplicationContent::new(
187            "my_call_id_1".to_owned(),
188            ruma::events::call::member::CallScope::Room,
189        );
190        app_content.call_intent = call_intent;
191
192        let application = Application::Call(app_content);
193        let foci_preferred = vec![Focus::Livekit(LivekitFocus::new(
194            "my_call_foci_alias".to_owned(),
195            "https://lk.org".to_owned(),
196        ))];
197        let focus_active = ActiveFocus::Livekit(ActiveLivekitFocus::new());
198
199        let (content, state_key) = match init_data {
200            Some(InitData { device_id, minutes_ago }) => {
201                let member_id = format!("{device_id}_m.call");
202                (
203                    CallMemberEventContent::new(
204                        application,
205                        device_id.to_owned(),
206                        focus_active,
207                        foci_preferred,
208                        Some(timestamp(minutes_ago)),
209                        None,
210                    ),
211                    CallMemberStateKey::new(user_id.to_owned(), Some(member_id), false),
212                )
213            }
214
215            None => (
216                CallMemberEventContent::new_empty(None),
217                CallMemberStateKey::new(user_id.to_owned(), None, false),
218            ),
219        };
220
221        EventFactory::new()
222            .sender(user_id)
223            .event(content)
224            .state_key(state_key.as_ref())
225            .event_id(ev_id)
226            // we can simply use now here since this will be dropped when using a MinimalStateEvent
227            // in the roomInfo
228            .server_ts(timestamp(0))
229            .into()
230    }
231
232    fn foci_and_application() -> (Application, Vec<Focus>) {
233        (
234            Application::Call(CallApplicationContent::new(
235                "my_call_id_1".to_owned(),
236                ruma::events::call::member::CallScope::Room,
237            )),
238            vec![Focus::Livekit(LivekitFocus::new(
239                "my_call_foci_alias".to_owned(),
240                "https://lk.org".to_owned(),
241            ))],
242        )
243    }
244
245    fn receive_state_events(room: &Room, events: Vec<Raw<AnySyncStateEvent>>) {
246        room.info.update_if(|info| {
247            let mut res = false;
248            for ev in events {
249                res |= info.handle_state_event(
250                    &mut RawStateEventWithKeys::try_from_raw_state_event(ev)
251                        .expect("generated state event should be valid"),
252                );
253            }
254            res
255        });
256    }
257
258    /// `user_a`: empty memberships
259    /// `user_b`: one membership
260    /// `user_c`: two memberships (two devices)
261    fn legacy_create_call_with_member_events_for_user(a: &UserId, b: &UserId, c: &UserId) -> Room {
262        let (_, room) = make_room_test_helper(RoomState::Joined);
263
264        let a_empty = legacy_member_state_event(Vec::new(), event_id!("$1234"), a);
265
266        // make b 10min old
267        let m_init_b = legacy_membership_for_my_call(device_id!("DEVICE_0"), "0", 1);
268        let b_one = legacy_member_state_event(vec![m_init_b], event_id!("$12345"), b);
269
270        // c1 1min old
271        let m_init_c1 = legacy_membership_for_my_call(device_id!("DEVICE_0"), "0", 10);
272        // c2 20min old
273        let m_init_c2 = legacy_membership_for_my_call(device_id!("DEVICE_1"), "0", 20);
274        let c_two = legacy_member_state_event(vec![m_init_c1, m_init_c2], event_id!("$123456"), c);
275
276        // Intentionally use a non time sorted receive order.
277        receive_state_events(&room, vec![c_two, a_empty, b_one]);
278
279        room
280    }
281
282    /// `user_a`: empty memberships
283    /// `user_b`: one membership
284    /// `user_c`: two memberships (two devices)
285    fn session_create_call_with_member_events_for_user(a: &UserId, b: &UserId, c: &UserId) -> Room {
286        let (_, room) = make_room_test_helper(RoomState::Joined);
287
288        let a_empty = session_member_state_event(event_id!("$1234"), a, None);
289
290        // make b 10min old
291        let b_one = session_member_state_event(
292            event_id!("$12345"),
293            b,
294            Some(InitData { device_id: "DEVICE_0".into(), minutes_ago: 1 }),
295        );
296
297        let m_c1 = session_member_state_event(
298            event_id!("$123456_0"),
299            c,
300            Some(InitData { device_id: "DEVICE_0".into(), minutes_ago: 10 }),
301        );
302        let m_c2 = session_member_state_event(
303            event_id!("$123456_1"),
304            c,
305            Some(InitData { device_id: "DEVICE_1".into(), minutes_ago: 20 }),
306        );
307        // Intentionally use a non time sorted receive order1
308        receive_state_events(&room, vec![m_c1, m_c2, a_empty, b_one]);
309
310        room
311    }
312
313    #[test]
314    fn test_show_correct_active_call_state() {
315        let room_legacy = legacy_create_call_with_member_events_for_user(&ALICE, &BOB, &CAROL);
316
317        // This check also tests the ordering.
318        // We want older events to be in the front.
319        // user_b (Bob) is 1min old, c1 (CAROL) 10min old, c2 (CAROL) 20min old
320        assert_eq!(
321            vec![CAROL.to_owned(), CAROL.to_owned(), BOB.to_owned()],
322            room_legacy.active_room_call_participants()
323        );
324        assert!(room_legacy.has_active_room_call());
325
326        let room_session = session_create_call_with_member_events_for_user(&ALICE, &BOB, &CAROL);
327        assert_eq!(
328            vec![CAROL.to_owned(), CAROL.to_owned(), BOB.to_owned()],
329            room_session.active_room_call_participants()
330        );
331        assert!(room_session.has_active_room_call());
332    }
333
334    #[test]
335    fn test_active_call_is_false_when_everyone_left() {
336        let room = legacy_create_call_with_member_events_for_user(&ALICE, &BOB, &CAROL);
337
338        let b_empty_membership = legacy_member_state_event(Vec::new(), event_id!("$1234_1"), &BOB);
339        let c_empty_membership =
340            legacy_member_state_event(Vec::new(), event_id!("$12345_1"), &CAROL);
341
342        receive_state_events(&room, vec![b_empty_membership, c_empty_membership]);
343
344        // We have no active call anymore after emptying the memberships
345        assert_eq!(Vec::<OwnedUserId>::new(), room.active_room_call_participants());
346        assert!(!room.has_active_room_call());
347    }
348
349    fn consensus_setup(
350        alice_intent: Option<CallIntent>,
351        bob_intent: Option<CallIntent>,
352        call_intent: Option<CallIntent>,
353    ) -> Vec<Raw<AnySyncStateEvent>> {
354        let alice_membership = session_member_state_event_with_intent(
355            event_id!("$1"),
356            user_id!("@alice:server.name"),
357            InitData { device_id: device_id!("AAA0"), minutes_ago: 1 }.into(),
358            alice_intent,
359        );
360        let bob_membership = session_member_state_event_with_intent(
361            event_id!("$1"),
362            user_id!("@bob:server.name"),
363            InitData { device_id: device_id!("BAA0"), minutes_ago: 1 }.into(),
364            bob_intent,
365        );
366        let carl_membership = session_member_state_event_with_intent(
367            event_id!("$2"),
368            user_id!("@carl:server.name"),
369            InitData { device_id: device_id!("CAA0"), minutes_ago: 1 }.into(),
370            call_intent,
371        );
372        vec![alice_membership, bob_membership, carl_membership]
373    }
374
375    #[test]
376    fn test_consensus_intent() {
377        let test_cases = vec![
378            // (alice_intent, bob_intent, carl_intent, expected_consensus, description)
379            (None, None, None, CallIntentConsensus::None, "no intents"),
380            (
381                Some(CallIntent::Audio),
382                None,
383                None,
384                CallIntentConsensus::Partial {
385                    intent: CallIntent::Audio,
386                    agreeing_count: 1,
387                    total_count: 3,
388                },
389                "one intent 1",
390            ),
391            (
392                None,
393                Some(CallIntent::Audio),
394                None,
395                CallIntentConsensus::Partial {
396                    intent: CallIntent::Audio,
397                    agreeing_count: 1,
398                    total_count: 3,
399                },
400                "one intent 2",
401            ),
402            (
403                None,
404                None,
405                Some(CallIntent::Audio),
406                CallIntentConsensus::Partial {
407                    intent: CallIntent::Audio,
408                    agreeing_count: 1,
409                    total_count: 3,
410                },
411                "one intent 3",
412            ),
413            (
414                None,
415                None,
416                Some(CallIntent::Video),
417                CallIntentConsensus::Partial {
418                    intent: CallIntent::Video,
419                    agreeing_count: 1,
420                    total_count: 3,
421                },
422                "one intent 4",
423            ),
424            (
425                None,
426                Some(CallIntent::Video),
427                Some(CallIntent::Video),
428                CallIntentConsensus::Partial {
429                    intent: CallIntent::Video,
430                    agreeing_count: 2,
431                    total_count: 3,
432                },
433                "two matching intents",
434            ),
435            (
436                Some(CallIntent::Video),
437                Some(CallIntent::Video),
438                Some(CallIntent::Video),
439                CallIntentConsensus::Full(CallIntent::Video),
440                "all agree",
441            ),
442            (
443                Some(CallIntent::Video),
444                None,
445                Some(CallIntent::Audio),
446                CallIntentConsensus::None,
447                "disagreement",
448            ),
449            (
450                Some(CallIntent::Video),
451                Some(CallIntent::Video),
452                Some(CallIntent::Audio),
453                CallIntentConsensus::None,
454                "disagreement 2",
455            ),
456        ];
457
458        for (alice, bob, carl, expected, description) in test_cases {
459            let (_, room) = make_room_test_helper(RoomState::Joined);
460            receive_state_events(&room, consensus_setup(alice, bob, carl));
461            let consensus_intent = room.active_room_call_consensus_intent();
462            assert_eq!(expected, consensus_intent, "Failed case: {}", description);
463        }
464    }
465
466    #[test]
467    fn is_device_in_active_room_call_matches_own_device_only() {
468        let (_, room) = make_room_test_helper(RoomState::Joined);
469
470        let alice_a = session_member_state_event(
471            event_id!("$alice_a"),
472            &ALICE,
473            Some(InitData { device_id: device_id!("DEVICE_A"), minutes_ago: 1 }),
474        );
475        let alice_b = session_member_state_event(
476            event_id!("$alice_b"),
477            &ALICE,
478            Some(InitData { device_id: device_id!("DEVICE_B"), minutes_ago: 1 }),
479        );
480        let bob_a = session_member_state_event(
481            event_id!("$bob_a"),
482            &BOB,
483            Some(InitData { device_id: device_id!("DEVICE_A"), minutes_ago: 1 }),
484        );
485
486        receive_state_events(&room, vec![alice_a, alice_b, bob_a]);
487
488        assert!(room.is_device_in_active_room_call(&ALICE, device_id!("DEVICE_A")));
489        assert!(room.is_device_in_active_room_call(&ALICE, device_id!("DEVICE_B")));
490        assert!(!room.is_device_in_active_room_call(&ALICE, device_id!("DEVICE_C")));
491        assert!(room.is_device_in_active_room_call(&BOB, device_id!("DEVICE_A")));
492        assert!(!room.is_device_in_active_room_call(&BOB, device_id!("DEVICE_B")));
493    }
494}