BlueGit

ict rusty-teams

Files

rusty-teams / crates / app-call-model / src / demo.rs

demo.rs

demo.rs 36.7 KiB Download Raw
1use std::time::{Duration, Instant};
2
3use calling::CameraDevice;
4use calling::video_frame::bgra_from_i420;
5use calling::video_pattern::{PatternKind, pattern_frame};
6use calling::{
7 AttendeeLimits, AudioDevice, BackgroundChoice, BreakoutMove, CallCommand, CallControl, CallHandle, CallHealth,
8 CallState, CallUpdate, Caller, CaptionEntry, CaptionState, ContentShare, DeviceChoice,
9 DeviceLists, EndReason, HealthSample, HoldState, IncomingRing, Limitation, MediaPath,
10 MeetingCapability, MeetingOptions, MeetingRole, MeetingTarget, Modality, NetworkLevel, Progress,
11 PublishedState, RaisedHand, Reaction, RecordingKind, Replacement, RosterEntry, ShareKind, ShareSource, StopScope,
12 TransportDetails, VideoKey, call_channel,
13};
14use calling::call::VideoReport;
15use calling::timeline::TimelineEntry;
16use calling::{CallDiagnostics, SdpLine, SdpSummary, StatsSample};
17
18use super::demo_scene::self_view;
19use super::end_screen::EndCause;
20use tokio::time::{interval, sleep};
21
22use super::model::{ECHO_MRI, ECHO_NAME};
23
24const CONNECT_DELAY: Duration = Duration::from_millis(2200);
25const RING_START: Duration = Duration::from_millis(1400);
26const ANSWER_DELAY: Duration = Duration::from_millis(3200);
27const INCOMING_CONNECT_DELAY: Duration = Duration::from_millis(600);
28const LOBBY_WAIT: Duration = Duration::from_secs(6);
29const LEVEL_PERIOD: Duration = Duration::from_millis(200);
30const SAMPLE_EVERY_TICKS: u32 = 10;
31const SAMPLE_PACKETS_PER_TICK: u64 = 10;
32const CYCLE_TICKS: u32 = 40;
33const REMOTE_SPEAKS: std::ops::Range<u32> = 0..18;
34const LOCAL_SPEAKS: std::ops::Range<u32> = 24..32;
35const SPEAKING_LEVEL: f32 = 0.3;
36const SPEAKER_TICKS: u32 = 10;
37const VIDEO_PERIOD: Duration = Duration::from_millis(125);
38const DEMO_CAMERAS: usize = 4;
39const GALLERY_CAMERAS: usize = 7;
40const GALLERY_SPEAKER_TICKS: u32 = 15;
41const SCREEN_EVERY_TICKS: u32 = 4;
42const SHARE_START: Duration = Duration::from_secs(10);
43const SHARE_END: Duration = Duration::from_secs(45);
44const REACTION_EVERY_TICKS: u32 = 20;
45const DEMO_FIRST_HANDS: [(usize, u64); 2] = [(2, 1), (0, 2)];
46const DEMO_WAITING: [&str; 3] = ["Anja Vogel", "Matteo Conti", "Hannah Weiss"];
47const CAPTION_WORDS_PER_TICK: usize = 2;
48const CAPTION_HOLD_TICKS: usize = 14;
49const DEMO_CAPTIONS: [(usize, &str); 4] = [
50 (
51 0,
52 "Thanks everyone for joining, let us start with the release status.",
53 ),
54 (
55 1,
56 "The build is green and the new call controls are ready for review.",
57 ),
58 (
59 2,
60 "Can we admit the two people from the lobby before we begin?",
61 ),
62 (
63 0,
64 "Yes, I am letting them in now and we will share the plan on screen.",
65 ),
66];
67const GUEST_PHASE: u32 = 37;
68const SELF_PHASE: u32 = 211;
69pub const DEMO_OWN_MRI: &str = "8:orgid:demo-me";
70pub const DEMO_RING_ID: u64 = 9001;
71const DEMO_CALLER: (&str, &str) = ("8:orgid:demo-mara", "Mara Lindqvist");
72const DEMO_GUESTS: [&str; 12] = [
73 "Mara Lindqvist",
74 "Jonas Ortega",
75 "Priya Nair",
76 "Lea Schneider",
77 "Tobias Klein",
78 "Ines Duarte",
79 "Noor Haddad",
80 "Felix Brandt",
81 "Yuki Tanaka",
82 "Carlos Mendez",
83 "Sofia Rossi",
84 "Emil Nowak",
85];
86
87pub type Person = (String, String);
88
89#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
90pub enum DemoScene {
91 #[default]
92 Plain,
93 Call,
94 Recording,
95 Consent,
96 Hold,
97 Held,
98 Consult,
99 Breakout,
100 Whiteboard,
101 Network,
102 Gallery,
103 Sharing,
104 Mini,
105 MiniOff,
106 MiniShare,
107 GalleryShare,
108 WindowShare,
109 Blocked,
110 Removed,
111 Dropped,
112}
113
114impl DemoScene {
115 pub fn from_name(name: &str) -> Option<Self> {
116 Some(match name.trim() {
117 "call" => DemoScene::Call,
118 "recording" => DemoScene::Recording,
119 "consent" => DemoScene::Consent,
120 "hold" => DemoScene::Hold,
121 "held" => DemoScene::Held,
122 "consult" => DemoScene::Consult,
123 "breakout" => DemoScene::Breakout,
124 "whiteboard" => DemoScene::Whiteboard,
125 "network" => DemoScene::Network,
126 "gallery" => DemoScene::Gallery,
127 "sharing" => DemoScene::Sharing,
128 "mini" => DemoScene::Mini,
129 "mini-off" => DemoScene::MiniOff,
130 "mini-share" => DemoScene::MiniShare,
131 "gallery-share" => DemoScene::GalleryShare,
132 "window-share" => DemoScene::WindowShare,
133 "blocked" => DemoScene::Blocked,
134 "removed" => DemoScene::Removed,
135 "dropped" => DemoScene::Dropped,
136 _ => return None,
137 })
138 }
139
140 pub fn is_one_to_one(self) -> bool {
141 matches!(
142 self,
143 DemoScene::Call
144 | DemoScene::Hold
145 | DemoScene::Held
146 | DemoScene::Consult
147 | DemoScene::Network
148 | DemoScene::Mini
149 | DemoScene::MiniOff
150 | DemoScene::MiniShare
151 | DemoScene::Blocked
152 )
153 }
154
155 pub fn end_cause(self) -> Option<EndCause> {
156 match self {
157 DemoScene::Removed => Some(EndCause::Removed),
158 DemoScene::Dropped => Some(EndCause::Dropped),
159 _ => None,
160 }
161 }
162
163 pub fn minimized(self) -> bool {
164 matches!(self, DemoScene::Mini | DemoScene::MiniOff | DemoScene::MiniShare)
165 }
166
167 pub fn guests(self) -> Option<usize> {
168 match self {
169 DemoScene::Gallery => Some(DEMO_GALLERY_GUESTS),
170 DemoScene::Sharing | DemoScene::GalleryShare | DemoScene::WindowShare => {
171 Some(DEMO_SHARING_GUESTS)
172 }
173 _ => None,
174 }
175 }
176
177 fn cameras(self) -> usize {
178 match self {
179 DemoScene::Gallery => GALLERY_CAMERAS,
180 DemoScene::MiniOff => 0,
181 _ => DEMO_CAMERAS,
182 }
183 }
184
185 fn speaker_ticks(self) -> u32 {
186 match self {
187 DemoScene::Gallery => GALLERY_SPEAKER_TICKS,
188 _ => SPEAKER_TICKS,
189 }
190 }
191}
192
193pub const DEMO_GALLERY_GUESTS: usize = 12;
194const DEMO_SHARING_GUESTS: usize = 9;
195const DEMO_SHARED_WINDOW: &str = "Standup board";
196const BREAKOUT_AT_TICKS: u32 = 20;
197const WHITEBOARD_AT_TICKS: u32 = 5;
198const DEMO_BOARD_URL: &str = "https://app.whiteboard.microsoft.com/me/whiteboards/demo";
199const DEMO_REPLACEMENT_LINK: &str = "https://demo.invalid/replacement";
200const DEMO_ROOM_THREAD: &str = "19:meeting_demo-room-1@thread.v2";
201
202pub enum DemoCall {
203 Test,
204 People(Vec<Person>),
205 Meeting {
206 guests: Vec<Person>,
207 lobby: bool,
208 organizer: bool,
209 },
210 Incoming(Person),
211}
212
213pub fn demo_guests(count: usize) -> Vec<Person> {
214 DEMO_GUESTS
215 .iter()
216 .take(count)
217 .enumerate()
218 .map(|(index, name)| (format!("8:orgid:demo-guest-{index}"), (*name).to_owned()))
219 .collect()
220}
221
222pub fn demo_caller() -> Person {
223 (DEMO_CALLER.0.to_owned(), DEMO_CALLER.1.to_owned())
224}
225
226pub fn demo_video_ring() -> IncomingRing {
227 IncomingRing {
228 video: true,
229 ..demo_ring()
230 }
231}
232
233pub fn demo_ring() -> IncomingRing {
234 let (mri, display_name) = demo_caller();
235 IncomingRing {
236 ring_id: DEMO_RING_ID,
237 caller: Caller { mri, display_name },
238 thread_id: Some("demo-chat-mara".to_owned()),
239 video: false,
240 is_group: false,
241 subject: None,
242 }
243}
244
245fn device(index: u16, name: &str) -> AudioDevice {
246 AudioDevice {
247 index,
248 guid: format!("demo-{index}"),
249 name: name.to_owned(),
250 }
251}
252
253fn demo_cameras() -> Vec<CameraDevice> {
254 vec![
255 CameraDevice {
256 key: "0".into(),
257 name: "Integrated Camera".into(),
258 },
259 CameraDevice {
260 key: "1".into(),
261 name: "Studio Webcam".into(),
262 },
263 ]
264}
265
266fn demo_share_sources() -> Vec<ShareSource> {
267 let window = |id: u64, title: &str| ShareSource {
268 id,
269 kind: ShareKind::Window,
270 title: title.to_owned(),
271 };
272 vec![
273 ShareSource {
274 id: 1,
275 kind: ShareKind::Screen,
276 title: String::new(),
277 },
278 window(2, "Release notes - Docs"),
279 window(3, DEMO_SHARED_WINDOW),
280 window(4, "Terminal"),
281 ]
282}
283
284fn demo_devices() -> DeviceLists {
285 DeviceLists {
286 inputs: vec![
287 device(0, "Headset Microphone"),
288 device(1, "Built-in Microphone"),
289 ],
290 outputs: vec![device(0, "Headset"), device(1, "Speakers")],
291 }
292}
293
294pub fn start_demo_call(script: DemoCall) -> CallHandle {
295 start_demo_scene_call(script, DemoScene::Plain)
296}
297
298pub fn start_demo_scene_call(script: DemoCall, scene: DemoScene) -> CallHandle {
299 let (handle, control) = call_channel();
300 app_base::runtime::handle().spawn(run_demo_call(control, script, scene));
301 handle
302}
303
304fn roster_of(people: &[Person], cameras: usize) -> Vec<RosterEntry> {
305 people
306 .iter()
307 .enumerate()
308 .map(|(index, (mri, name))| RosterEntry {
309 mri: mri.clone(),
310 display_name: name.clone(),
311 muted: index % 3 == 1,
312 in_lobby: false,
313 has_video: index < cameras,
314 sharing: false,
315 hand: None,
316 spotlight: None,
317 role: Some(demo_role(index)),
318 limits: demo_limits(index),
319 organizer: false,
320 })
321 .collect()
322}
323
324async fn run_demo_call(mut control: CallControl, script: DemoCall, scene: DemoScene) {
325 control.send(CallUpdate::OwnIdentity {
326 mri: DEMO_OWN_MRI.to_owned(),
327 });
328 let (people, lobby) = match &script {
329 DemoCall::Test => (vec![(ECHO_MRI.to_owned(), ECHO_NAME.to_owned())], false),
330 DemoCall::People(callees) => (callees.clone(), false),
331 DemoCall::Meeting { guests, lobby, .. } => (guests.clone(), *lobby),
332 DemoCall::Incoming(caller) => (vec![caller.clone()], false),
333 };
334 if !ring_until_answered(&mut control, &script).await {
335 end(&control, EndReason::Cancelled);
336 return;
337 }
338 control.send(CallUpdate::ListenOnly(false));
339 control.send(CallUpdate::Devices(demo_devices()));
340 control.send(CallUpdate::Cameras(demo_cameras()));
341 control.send(CallUpdate::ShareSources(demo_share_sources()));
342 control.send(CallUpdate::Selected {
343 input: DeviceChoice::SystemDefault,
344 output: DeviceChoice::SystemDefault,
345 });
346 control.send(CallUpdate::State(CallState::Connected {
347 since: Instant::now(),
348 }));
349 if lobby {
350 control.send(CallUpdate::Lobby(true));
351 if control.until_hangup(sleep(LOBBY_WAIT)).await.is_err() {
352 end(&control, EndReason::LocalHangup);
353 return;
354 }
355 control.send(CallUpdate::Lobby(false));
356 }
357 let mut roster = roster_of(&people, scene.cameras());
358 if scene == DemoScene::Sharing {
359 roster.push(RosterEntry { mri: calling::captions::RECORDING_BOT_MRI.to_owned(), ..RosterEntry::default() });
360 }
361 if matches!(script, DemoCall::People(_)) {
362 control.send(CallUpdate::ReplacementLink(Replacement::of_call(
363 DEMO_REPLACEMENT_LINK,
364 )));
365 }
366 if matches!(
367 script,
368 DemoCall::Meeting {
369 organizer: true,
370 ..
371 }
372 ) {
373 roster.push(demo_organizer());
374 roster.extend(
375 DEMO_WAITING
376 .iter()
377 .enumerate()
378 .map(|(index, name)| demo_waiting(index, name)),
379 );
380 }
381 if matches!(script, DemoCall::Meeting { .. }) {
382 for (index, rank) in DEMO_FIRST_HANDS {
383 if let Some(entry) = roster.get_mut(index) {
384 entry.hand = Some(demo_hand(rank));
385 }
386 }
387 }
388 control.send(CallUpdate::Roster(roster.clone()));
389 let video = !matches!(script, DemoCall::Test);
390 let sharer = matches!(script, DemoCall::Meeting { .. })
391 .then(|| people.get(1).map(|person| person.0.clone()))
392 .flatten()
393 .filter(|_| scene != DemoScene::Gallery);
394 start_scene(&control, scene);
395 speak_until_hangup(control, people, roster, video, sharer, scene).await;
396}
397
398async fn ring_until_answered(control: &mut CallControl, script: &DemoCall) -> bool {
399 let steps: Vec<(Option<Progress>, Duration)> = match script {
400 DemoCall::People(_) => vec![
401 (Some(Progress::Calling), RING_START),
402 (Some(Progress::Ringing), ANSWER_DELAY - RING_START),
403 ],
404 DemoCall::Incoming(_) => vec![(None, INCOMING_CONNECT_DELAY)],
405 DemoCall::Test | DemoCall::Meeting { .. } => vec![(None, CONNECT_DELAY)],
406 };
407 for (progress, wait) in steps {
408 if let Some(progress) = progress {
409 control.send(CallUpdate::Progress(progress));
410 }
411 if control.until_hangup(sleep(wait)).await.is_err() {
412 return false;
413 }
414 }
415 true
416}
417
418fn publish_demo_video(
419 control: &CallControl,
420 people: &[Person],
421 tick: u32,
422 sharing: bool,
423 sharer: Option<&str>,
424 camera: Option<bool>,
425 cameras: usize,
426) {
427 if let Some(blur) = camera {
428 control.video.publish(
429 VideoKey::LocalCamera,
430 self_view((tick + SELF_PHASE) as usize, blur),
431 );
432 }
433 for (index, (mri, _)) in people.iter().take(cameras).enumerate() {
434 let frame = pattern_frame(PatternKind::Camera, tick + index as u32 * GUEST_PHASE);
435 control
436 .video
437 .publish(VideoKey::Person(mri.clone()), bgra_from_i420(frame));
438 }
439 if sharing && sharer.is_some() && tick.is_multiple_of(SCREEN_EVERY_TICKS) {
440 control.video.publish(
441 VideoKey::Screen,
442 bgra_from_i420(pattern_frame(PatternKind::Screen, tick)),
443 );
444 }
445}
446
447fn start_scene(control: &CallControl, scene: DemoScene) {
448 match scene {
449 DemoScene::Recording => {
450 control.send(CallUpdate::Recording(true));
451 control.send(CallUpdate::Transcribing(true));
452 control.send(CallUpdate::Captions(CaptionState::On));
453 }
454 DemoScene::Consent => {
455 control.send(CallUpdate::Recording(true));
456 control.send(CallUpdate::ConsentRequired(true));
457 }
458 DemoScene::Hold => control.send(CallUpdate::Hold(HoldState::Local)),
459 DemoScene::Held => control.send(CallUpdate::Hold(HoldState::Remote)),
460 DemoScene::Network => control.send(CallUpdate::Health(poor_network_health())),
461 DemoScene::MiniShare | DemoScene::GalleryShare => {
462 control.send(CallUpdate::LocalShare(Some("Entire screen".to_owned())))
463 }
464 DemoScene::WindowShare => {
465 control.send(CallUpdate::LocalShare(Some(DEMO_SHARED_WINDOW.to_owned())))
466 }
467 DemoScene::Call
468 | DemoScene::Mini
469 | DemoScene::MiniOff
470 | DemoScene::Consult
471 | DemoScene::Breakout
472 | DemoScene::Whiteboard
473 | DemoScene::Gallery
474 | DemoScene::Sharing
475 | DemoScene::Blocked
476 | DemoScene::Removed
477 | DemoScene::Dropped
478 | DemoScene::Plain => {}
479 }
480}
481
482fn poor_network_health() -> CallHealth {
483 CallHealth {
484 level: NetworkLevel::Poor,
485 cpu_limited: false,
486 sample: HealthSample {
487 loss_percent: 7.2,
488 round_trip_ms: 310.,
489 jitter_ms: 38.,
490 sent_kbps: 420.,
491 received_kbps: 1180.,
492 limitation: Limitation::Bandwidth,
493 },
494 transport: TransportDetails {
495 dtls_state: "Connected".to_owned(),
496 tls_version: "FEFD".to_owned(),
497 dtls_cipher: "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256".to_owned(),
498 srtp_cipher: "AEAD_AES_128_GCM".to_owned(),
499 local_fingerprint: String::new(),
500 remote_fingerprint: String::new(),
501 },
502 path: MediaPath::Direct,
503 }
504}
505
506fn scene_tick(control: &CallControl, scene: DemoScene, ticks: u32, people: &[Person]) {
507 match scene {
508 DemoScene::Breakout if ticks == BREAKOUT_AT_TICKS => {
509 control.send(CallUpdate::BreakoutMove(BreakoutMove {
510 room_name: "Room 1".to_owned(),
511 target: MeetingTarget {
512 thread_id: DEMO_ROOM_THREAD.to_owned(),
513 tenant_id: "demo-tenant".to_owned(),
514 organizer_id: "demo-me".to_owned(),
515 meeting_data: None,
516 },
517 returning: false,
518 }))
519 }
520 DemoScene::Whiteboard if ticks == WHITEBOARD_AT_TICKS => {
521 control.send(CallUpdate::Whiteboard(Some(ContentShare {
522 session_id: "demo-whiteboard".to_owned(),
523 presenter: people.first().map(|person| person.0.clone()),
524 subject: "Whiteboard".to_owned(),
525 url: Some(DEMO_BOARD_URL.to_owned()),
526 whiteboard: true,
527 })))
528 }
529 _ => {}
530 }
531}
532
533async fn speak_until_hangup(
534 mut control: CallControl,
535 people: Vec<Person>,
536 mut roster: Vec<RosterEntry>,
537 video: bool,
538 sharer: Option<String>,
539 scene: DemoScene,
540) {
541 let started = Instant::now();
542 let mut video_ticks = 0u32;
543 let mut sharing = false;
544 let mut camera_on = false;
545 let mut incoming_video = true;
546 let mut blur = false;
547 let mut captions_on = scene == DemoScene::Recording;
548 let mut recording_on = matches!(scene, DemoScene::Recording | DemoScene::Consent);
549 let mut transcribing_on = scene == DemoScene::Recording;
550 let mut caption_ticks = 0usize;
551 let mut video_tick = interval(VIDEO_PERIOD);
552 let mut muted = false;
553 let mut input = DeviceChoice::SystemDefault;
554 let mut output = DeviceChoice::SystemDefault;
555 let mut ticks = 0u32;
556 let mut share_sound = false;
557 let mut capability = MeetingCapability::default();
558 let mut tick = interval(LEVEL_PERIOD);
559 loop {
560 tokio::select! {
561 _ = video_tick.tick(), if video || camera_on => {
562 let elapsed = started.elapsed();
563 let share_now = sharer.is_some() && (scene == DemoScene::Sharing || (SHARE_START..SHARE_END).contains(&elapsed));
564 if share_now != sharing {
565 sharing = share_now;
566 control.send(CallUpdate::ScreenShare(sharer.clone().filter(|_| sharing)));
567 }
568 publish_demo_video(&control, if incoming_video { people.as_slice() } else { &[] }, video_ticks, sharing, sharer.as_deref(), camera_on.then_some(blur), scene.cameras());
569 video_ticks += 1;
570 }
571 _ = tick.tick() => {
572 let phase = ticks % CYCLE_TICKS;
573 let remote_speaks = REMOTE_SPEAKS.contains(&phase);
574 control.send(CallUpdate::Levels {
575 local: if LOCAL_SPEAKS.contains(&phase) && !muted { SPEAKING_LEVEL } else { 0.0 },
576 remote: if remote_speaks { SPEAKING_LEVEL } else { 0.0 },
577 });
578 if people.len() > 1 && ticks.is_multiple_of(scene.speaker_ticks()) {
579 let speaker = &people[(ticks / scene.speaker_ticks()) as usize % people.len()];
580 control.send(CallUpdate::Speakers(vec![speaker.0.clone()]));
581 }
582 if ticks % REACTION_EVERY_TICKS == REACTION_EVERY_TICKS / 2
583 && let Some((mri, _)) = people.get((ticks / REACTION_EVERY_TICKS) as usize % people.len().max(1))
584 {
585 let reaction = Reaction::ALL[(ticks / REACTION_EVERY_TICKS) as usize % Reaction::ALL.len()].clone();
586 control.send(CallUpdate::Reaction { mri: mri.clone(), reaction });
587 }
588 if captions_on {
589 if let Some(entry) = demo_caption(&people, caption_ticks) {
590 control.send(CallUpdate::Caption(entry));
591 }
592 caption_ticks += 1;
593 }
594 if ticks.is_multiple_of(SAMPLE_EVERY_TICKS) {
595 control.send(CallUpdate::Sample(demo_sample(ticks, video)));
596 }
597 scene_tick(&control, scene, ticks, &people);
598 ticks += 1;
599 }
600 command = control.recv() => match command {
601 Some(CallCommand::Mute(command)) => {
602 muted = command.target(muted);
603 control.send(CallUpdate::Muted(muted));
604 }
605 Some(CallCommand::DisableAudio) => {
606 muted = true;
607 control.send(CallUpdate::Muted(muted));
608 }
609 Some(CallCommand::SelectInput(choice)) => {
610 input = choice;
611 control.send(CallUpdate::Selected { input: input.clone(), output: output.clone() });
612 }
613 Some(CallCommand::SelectOutput(choice)) => {
614 output = choice;
615 control.send(CallUpdate::Selected { input: input.clone(), output: output.clone() });
616 }
617 Some(CallCommand::RefreshDevices) => control.send(CallUpdate::Devices(demo_devices())),
618 Some(CallCommand::SetCamera(on)) => {
619 camera_on = on;
620 control.send(CallUpdate::Camera(on));
621 }
622 Some(CallCommand::SelectCamera(_) | CallCommand::SetMicSettings(_)) => {}
623 Some(CallCommand::StartShare(source)) => {
624 control.send(CallUpdate::LocalShare(Some(source.label())));
625 if share_sound {
626 control.send(CallUpdate::ShareSound(true));
627 }
628 }
629 Some(CallCommand::StopShare) => control.send(CallUpdate::LocalShare(None)),
630 Some(CallCommand::SetShareSound(on)) => share_sound = on,
631 Some(CallCommand::SetHand(raised)) => {
632 set_demo_hand(&mut roster, DEMO_OWN_MRI, raised);
633 control.send(CallUpdate::Roster(roster.clone()));
634 }
635 Some(CallCommand::LowerHand { mri }) => {
636 set_demo_hand(&mut roster, &mri, false);
637 control.send(CallUpdate::Roster(roster.clone()));
638 }
639 Some(CallCommand::LowerAllHands) => {
640 roster.iter_mut().for_each(|entry| entry.hand = None);
641 control.send(CallUpdate::Roster(roster.clone()));
642 }
643 Some(CallCommand::SendReaction(reaction)) => {
644 control.send(CallUpdate::Reaction { mri: DEMO_OWN_MRI.to_owned(), reaction });
645 }
646 Some(CallCommand::Admit { mri }) => {
647 roster.iter_mut().filter(|entry| entry.mri == mri).for_each(|entry| entry.in_lobby = false);
648 control.send(CallUpdate::Roster(roster.clone()));
649 }
650 Some(CallCommand::AdmitAll) => {
651 roster.iter_mut().for_each(|entry| entry.in_lobby = false);
652 control.send(CallUpdate::Roster(roster.clone()));
653 }
654 Some(CallCommand::Deny { mri } | CallCommand::RemoveParticipant { mri }) => {
655 roster.retain(|entry| entry.mri != mri);
656 control.send(CallUpdate::Roster(roster.clone()));
657 }
658 Some(CallCommand::MuteParticipant { mri }) => {
659 roster.iter_mut().filter(|entry| entry.mri == mri).for_each(|entry| entry.muted = true);
660 control.send(CallUpdate::Roster(roster.clone()));
661 }
662 Some(CallCommand::MuteAll) => {
663 roster.iter_mut().filter(|entry| entry.mri != DEMO_OWN_MRI).for_each(|entry| entry.muted = true);
664 control.send(CallUpdate::Roster(roster.clone()));
665 }
666 Some(CallCommand::SetLock(locked)) => {
667 capability.locked = locked;
668 control.send(CallUpdate::Capability(capability));
669 }
670 Some(CallCommand::SetRole { mri, role }) => {
671 roster.iter_mut().filter(|entry| entry.mri == mri).for_each(|entry| entry.role = Some(role));
672 control.send(CallUpdate::Roster(roster.clone()));
673 }
674 Some(CallCommand::SetAttendeeModality { mri, modality, allowed }) => {
675 if let Some(entry) = roster.iter_mut().find(|entry| entry.mri == mri) {
676 let (blocked, released) = match modality {
677 Modality::Mic => (&mut entry.limits.mic_blocked, &mut entry.limits.mic_released),
678 Modality::Camera => (&mut entry.limits.camera_blocked, &mut entry.limits.camera_released),
679 };
680 *blocked = (!allowed).then(|| demo_state("demo-blocked", 1));
681 *released = None;
682 }
683 control.send(CallUpdate::Roster(roster.clone()));
684 }
685 Some(CallCommand::SetAttendeeRestrictions { mic_off, camera_off }) => {
686 capability.attendee_mic_off = mic_off;
687 capability.attendee_camera_off = camera_off;
688 control.send(CallUpdate::Capability(capability));
689 }
690 Some(CallCommand::Invite { callees, .. }) => {
691 for callee in callees {
692 roster.push(RosterEntry { mri: callee.mri, display_name: callee.display_name, role: Some(MeetingRole::Attendee), ..RosterEntry::default() });
693 }
694 control.send(CallUpdate::Roster(roster.clone()));
695 }
696 Some(CallCommand::LoadMeetingOptions) => control.send(CallUpdate::MeetingOptions(Ok(demo_options()))),
697 Some(CallCommand::SaveMeetingOptions(_)) => control.send(CallUpdate::MeetingOptionsSaved(Ok(demo_options()))),
698 Some(CallCommand::Spotlight { mri }) => {
699 let rank = roster.iter().filter_map(|entry| entry.spotlight.as_ref().map(|state| state.rank)).max().unwrap_or(0) + 1;
700 if let Some(entry) = roster.iter_mut().find(|entry| entry.mri == mri) {
701 entry.spotlight = Some(demo_spotlight(rank));
702 }
703 control.send(CallUpdate::Roster(roster.clone()));
704 }
705 Some(CallCommand::StopSpotlight { mri }) => {
706 roster.iter_mut().filter(|entry| entry.mri == mri).for_each(|entry| entry.spotlight = None);
707 control.send(CallUpdate::Roster(roster.clone()));
708 }
709 Some(CallCommand::SetCaptions(on)) => {
710 captions_on = on;
711 caption_ticks = 0;
712 control.send(CallUpdate::Captions(if on { CaptionState::On } else { CaptionState::Off }));
713 }
714 Some(CallCommand::SetBackground(choice)) => blur = choice != BackgroundChoice::None,
715 Some(CallCommand::SetIncomingVideo(enabled)) => {
716 incoming_video = enabled;
717 people.iter().for_each(|(mri, _)| control.video.forget(&VideoKey::Person(mri.clone())));
718 control.send(CallUpdate::IncomingVideo(enabled));
719 }
720 Some(CallCommand::SetCameraEffects(_) | CallCommand::SetVideoWants(_) | CallCommand::SetShareMotion(_) | CallCommand::SetShareStandout(_)) => {}
721 Some(CallCommand::StartRecording { kind, .. }) => {
722 recording_on = kind != RecordingKind::TranscriptOnly;
723 transcribing_on = true;
724 control.send(CallUpdate::Recording(recording_on));
725 control.send(CallUpdate::RecordingAudioOnly(kind == RecordingKind::AudioOnly));
726 control.send(CallUpdate::Transcribing(true));
727 }
728 Some(CallCommand::StopRecording { scope }) => {
729 recording_on = recording_on && scope == StopScope::TranscriptionOnly;
730 transcribing_on = transcribing_on && scope == StopScope::RecordingOnly;
731 control.send(CallUpdate::Recording(recording_on));
732 control.send(CallUpdate::Transcribing(transcribing_on));
733 }
734 Some(CallCommand::SetCaptionLanguage(_)) => {}
735 Some(CallCommand::ConsentToRecording) => control.send(CallUpdate::ConsentRequired(false)),
736 Some(CallCommand::Hold(hold)) => control.send(CallUpdate::Hold(if hold { HoldState::Local } else { HoldState::Active })),
737 Some(CallCommand::Transfer { .. }) => {
738 control.send(CallUpdate::TransferResult { succeeded: true });
739 control.send(CallUpdate::Notice("Call transferred".to_owned()));
740 end(&control, EndReason::LocalHangup);
741 return;
742 }
743 Some(CallCommand::OpenWhiteboard { .. }) => control.send(CallUpdate::WhiteboardUrl(DEMO_BOARD_URL.to_owned())),
744 Some(CallCommand::RefreshShareSources) => control.send(CallUpdate::ShareSources(demo_share_sources())),
745 Some(CallCommand::Hangup | CallCommand::EndMeeting) | None => {
746 end(&control, EndReason::LocalHangup);
747 return;
748 }
749 },
750 }
751 }
752}
753
754fn demo_role(index: usize) -> MeetingRole {
755 match index {
756 3 => MeetingRole::Organizer,
757 0 | 1 => MeetingRole::Presenter,
758 _ => MeetingRole::Attendee,
759 }
760}
761
762fn demo_limits(index: usize) -> AttendeeLimits {
763 AttendeeLimits {
764 mic_blocked: (index == 5).then(|| demo_state("demo-blocked-5", 1)),
765 ..AttendeeLimits::default()
766 }
767}
768
769fn demo_state(id: &str, rank: u64) -> PublishedState {
770 PublishedState { state_id: id.to_owned(), rank }
771}
772
773fn demo_options() -> MeetingOptions {
774 let option = |name: &str, value: serde_json::Value| serde_json::json!({"name": name, "currentValue": value});
775 MeetingOptions::from_response(&serde_json::json!({"options": [
776 option("AutoAdmittedUsers", serde_json::json!("EveryoneInCompany")),
777 option("PresenterOption", serde_json::json!("Everyone")),
778 option("AttendeeRestrictions", serde_json::json!("UnRestricted")),
779 option("AllowMeetingChat", serde_json::json!("Enabled")),
780 option("AllowTeamsMeetingReactions", serde_json::json!(true)),
781 option("AutoRecordAndTranscribeMode", serde_json::json!("Off")),
782 ]}))
783 .expect("the demo options are complete")
784}
785
786fn demo_organizer() -> RosterEntry {
787 RosterEntry {
788 mri: DEMO_OWN_MRI.to_owned(),
789 display_name: "You".to_owned(),
790 muted: false,
791 in_lobby: false,
792 has_video: false,
793 sharing: false,
794 hand: None,
795 spotlight: None,
796 organizer: true,
797 role: Some(MeetingRole::Organizer),
798 ..Default::default()
799 }
800}
801
802fn demo_waiting(index: usize, name: &str) -> RosterEntry {
803 RosterEntry {
804 mri: format!("8:orgid:demo-waiting-{index}"),
805 display_name: name.to_owned(),
806 muted: false,
807 in_lobby: true,
808 has_video: false,
809 sharing: false,
810 hand: None,
811 spotlight: None,
812 organizer: false,
813 ..Default::default()
814 }
815}
816
817fn demo_spotlight(rank: u64) -> PublishedState {
818 PublishedState {
819 state_id: format!("demo-spotlight-{rank}"),
820 rank,
821 }
822}
823
824fn demo_caption(people: &[Person], tick: usize) -> Option<CaptionEntry> {
825 let line = tick / (CAPTION_HOLD_TICKS * 2);
826 if line >= DEMO_CAPTIONS.len() {
827 return None;
828 }
829 let within = tick % (CAPTION_HOLD_TICKS * 2);
830 let (speaker, text) = DEMO_CAPTIONS[line];
831 let words: Vec<&str> = text.split(' ').collect();
832 let shown = ((within + 1) * CAPTION_WORDS_PER_TICK).min(words.len());
833 let (mri, name) = people.get(speaker % people.len().max(1))?;
834 Some(CaptionEntry {
835 id: format!("demo-caption-{}", tick / (CAPTION_HOLD_TICKS * 2)),
836 user_id: mri.clone(),
837 display_name: name.clone(),
838 text: words[..shown].join(" "),
839 is_final: shown == words.len(),
840 })
841}
842
843fn demo_hand(rank: u64) -> RaisedHand {
844 RaisedHand {
845 state_id: format!("demo-hand-{rank}"),
846 rank,
847 }
848}
849
850fn set_demo_hand(roster: &mut Vec<RosterEntry>, mri: &str, raised: bool) {
851 let next_rank = roster
852 .iter()
853 .filter_map(|entry| entry.hand.as_ref().map(|hand| hand.rank))
854 .max()
855 .unwrap_or(0)
856 + 1;
857 if !raised {
858 if let Some(entry) = roster.iter_mut().find(|entry| entry.mri == mri) {
859 entry.hand = None;
860 }
861 roster.retain(|entry| entry.mri != DEMO_OWN_MRI || entry.hand.is_some());
862 return;
863 }
864 match roster.iter_mut().find(|entry| entry.mri == mri) {
865 Some(entry) => entry.hand = Some(demo_hand(next_rank)),
866 None => roster.push(RosterEntry {
867 mri: mri.to_owned(),
868 display_name: "You".to_owned(),
869 muted: false,
870 in_lobby: false,
871 has_video: false,
872 sharing: false,
873 hand: Some(demo_hand(next_rank)),
874 spotlight: None,
875 organizer: false,
876 ..Default::default()
877 }),
878 }
879}
880
881fn end(control: &CallControl, reason: EndReason) {
882 control.send(CallUpdate::State(CallState::Ended { reason }));
883 control.send(CallUpdate::Diagnostics(Box::new(demo_diagnostics())));
884}
885
886fn demo_sample(ticks: u32, video: bool) -> StatsSample {
887 let packets = u64::from(ticks) * SAMPLE_PACKETS_PER_TICK;
888 StatsSample {
889 audio_in_packets: packets,
890 audio_out_packets: packets,
891 audio_in_level: 0.05,
892 audio_out_level: 0.04,
893 video: if video {
894 VideoReport {
895 inbound_packets: packets * 4,
896 inbound_frames_decoded: packets,
897 inbound_width: 1280,
898 inbound_height: 720,
899 outbound_packets: packets * 3,
900 outbound_frames_encoded: packets,
901 outbound_width: 640,
902 outbound_height: 360,
903 ..VideoReport::default()
904 }
905 } else {
906 VideoReport::default()
907 },
908 ..StatsSample::default()
909 }
910}
911
912fn demo_diagnostics() -> CallDiagnostics {
913 let entry = |elapsed_ms: u128, label: &str, detail: &str| TimelineEntry {
914 elapsed_ms,
915 label: label.to_owned(),
916 detail: detail.to_owned(),
917 };
918 let line = |kind: &str, mid: &str, codecs: &[&str]| SdpLine {
919 kind: kind.to_owned(),
920 mid: mid.to_owned(),
921 direction: "sendrecv".to_owned(),
922 codecs: codecs.iter().map(|codec| (*codec).to_owned()).collect(),
923 payload_count: codecs.len(),
924 ssrc_count: 1,
925 rejected: false,
926 };
927 CallDiagnostics {
928 timeline: vec![
929 entry(5, "Trouter connected", "callback socket ready"),
930 entry(40, "setLocalDescription", "2 m-line(s) signaled"),
931 entry(900, "ICE state", "Connected"),
932 entry(950, "PeerConnection state", "Connected"),
933 ],
934 sdp: vec![
935 SdpSummary { at_ms: 40, role: "local offer".to_owned(), lines: vec![line("audio", "0", &["opus"]), line("video", "1", &["H264"])] },
936 SdpSummary { at_ms: 800, role: "remote answer".to_owned(), lines: vec![line("audio", "0", &["opus"]), line("video", "1", &["H264"])] },
937 ],
938 ice_connected_ms: Some(900),
939 peer_connected_ms: Some(950),
940 selected_pair: Some("local Host/udp <-> remote Host/udp".to_owned()),
941 tls_version: "1.2".to_owned(),
942 dtls_cipher: "demo".to_owned(),
943 srtp_cipher: "demo".to_owned(),
944 }
945}
946
947#[cfg(test)]
948mod tests {
949 use super::*;
950
951 #[test]
952 fn demo_guests_have_distinct_mris_and_names() {
953 let guests = demo_guests(12);
954 assert_eq!(guests.len(), 12);
955 let mut mris: Vec<&String> = guests.iter().map(|guest| &guest.0).collect();
956 mris.sort();
957 mris.dedup();
958 assert_eq!(mris.len(), 12);
959 }
960
961 #[test]
962 fn demo_hands_queue_in_order_and_lowering_drops_the_own_entry() {
963 let mut roster = roster_of(&demo_guests(3), DEMO_CAMERAS);
964 set_demo_hand(&mut roster, "8:orgid:demo-guest-1", true);
965 set_demo_hand(&mut roster, DEMO_OWN_MRI, true);
966 let ranks: Vec<u64> = roster
967 .iter()
968 .filter_map(|entry| entry.hand.as_ref().map(|hand| hand.rank))
969 .collect();
970 assert_eq!(ranks, vec![1, 2]);
971 set_demo_hand(&mut roster, DEMO_OWN_MRI, false);
972 assert!(roster.iter().all(|entry| entry.mri != DEMO_OWN_MRI));
973 }
974
975 #[test]
976 fn demo_captions_stop_after_the_last_line() {
977 let people = demo_guests(3);
978 let ticks_per_line = CAPTION_HOLD_TICKS * 2;
979 assert!(demo_caption(&people, ticks_per_line * DEMO_CAPTIONS.len() - 1).is_some());
980 assert!(demo_caption(&people, ticks_per_line * DEMO_CAPTIONS.len()).is_none());
981 }
982
983 #[test]
984 fn the_demo_ring_names_a_caller_and_a_chat() {
985 let ring = demo_ring();
986 assert_eq!(ring.caller.display_name, "Mara Lindqvist");
987 assert_eq!(ring.thread_id.as_deref(), Some("demo-chat-mara"));
988 }
989}