BlueGit

ict rusty-teams

Files

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

demo.rs

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