BlueGit

ict rusty-teams

Files

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

demo.rs

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