BlueGit

ict rusty-teams

Files

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

demo.rs

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