BlueGit

ict rusty-teams

Files

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

demo.rs

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