BlueGit

ict rusty-teams

Files

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

demo.rs

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