BlueGit

ict rusty-teams

Files

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

demo.rs

demo.rs 25.5 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 AudioDevice, BackgroundChoice, BreakoutMove, CallCommand, CallControl, CallHandle, CallHealth,
8 CallState, CallUpdate, Caller, CaptionEntry, CaptionState, ContentShare, DeviceChoice,
9 DeviceLists, EndReason, HealthSample, HoldState, IncomingRing, Limitation, MediaPath,
10 MeetingTarget, NetworkLevel, Progress, PublishedState, RaisedHand, Reaction, RosterEntry,
11 ShareKind, ShareSource, TransportDetails, VideoKey, call_channel,
12};
13
14use super::demo_scene::self_view;
15use tokio::time::{interval, sleep};
16
17use super::model::{ECHO_MRI, ECHO_NAME};
18
19const CONNECT_DELAY: Duration = Duration::from_millis(2200);
20const RING_START: Duration = Duration::from_millis(1400);
21const ANSWER_DELAY: Duration = Duration::from_millis(3200);
22const INCOMING_CONNECT_DELAY: Duration = Duration::from_millis(600);
23const LOBBY_WAIT: Duration = Duration::from_secs(6);
24const LEVEL_PERIOD: Duration = Duration::from_millis(200);
25const CYCLE_TICKS: u32 = 40;
26const REMOTE_SPEAKS: std::ops::Range<u32> = 0..18;
27const LOCAL_SPEAKS: std::ops::Range<u32> = 24..32;
28const SPEAKING_LEVEL: f32 = 0.3;
29const SPEAKER_TICKS: u32 = 10;
30const VIDEO_PERIOD: Duration = Duration::from_millis(125);
31const DEMO_CAMERAS: usize = 4;
32const SCREEN_EVERY_TICKS: u32 = 4;
33const SHARE_START: Duration = Duration::from_secs(10);
34const SHARE_END: Duration = Duration::from_secs(45);
35const REACTION_EVERY_TICKS: u32 = 20;
36const DEMO_FIRST_HANDS: [(usize, u64); 2] = [(2, 1), (0, 2)];
37const DEMO_WAITING: [&str; 3] = ["Anja Vogel", "Matteo Conti", "Hannah Weiss"];
38const CAPTION_WORDS_PER_TICK: usize = 2;
39const CAPTION_HOLD_TICKS: usize = 14;
40const DEMO_CAPTIONS: [(usize, &str); 4] = [
41 (
42 0,
43 "Thanks everyone for joining, let us start with the release status.",
44 ),
45 (
46 1,
47 "The build is green and the new call controls are ready for review.",
48 ),
49 (
50 2,
51 "Can we admit the two people from the lobby before we begin?",
52 ),
53 (
54 0,
55 "Yes, I am letting them in now and we will share the plan on screen.",
56 ),
57];
58const GUEST_PHASE: u32 = 37;
59const SELF_PHASE: u32 = 211;
60pub const DEMO_OWN_MRI: &str = "8:orgid:demo-me";
61pub const DEMO_RING_ID: u64 = 9001;
62const DEMO_CALLER: (&str, &str) = ("8:orgid:demo-mara", "Mara Lindqvist");
63const DEMO_GUESTS: [&str; 11] = [
64 "Mara Lindqvist",
65 "Jonas Ortega",
66 "Priya Nair",
67 "Lea Schneider",
68 "Tobias Klein",
69 "Ines Duarte",
70 "Noor Haddad",
71 "Felix Brandt",
72 "Yuki Tanaka",
73 "Carlos Mendez",
74 "Sofia Rossi",
75];
76
77pub type Person = (String, String);
78
79#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
80pub enum DemoScene {
81 #[default]
82 Plain,
83 Call,
84 Recording,
85 Consent,
86 Hold,
87 Held,
88 Breakout,
89 Whiteboard,
90 Network,
91}
92
93impl DemoScene {
94 pub fn from_name(name: &str) -> Option<Self> {
95 Some(match name.trim() {
96 "call" => DemoScene::Call,
97 "recording" => DemoScene::Recording,
98 "consent" => DemoScene::Consent,
99 "hold" => DemoScene::Hold,
100 "held" => DemoScene::Held,
101 "breakout" => DemoScene::Breakout,
102 "whiteboard" => DemoScene::Whiteboard,
103 "network" => DemoScene::Network,
104 _ => return None,
105 })
106 }
107
108 pub fn is_one_to_one(self) -> bool {
109 matches!(self, DemoScene::Call | DemoScene::Hold | DemoScene::Held | DemoScene::Network)
110 }
111}
112
113const BREAKOUT_AT_TICKS: u32 = 20;
114const WHITEBOARD_AT_TICKS: u32 = 5;
115const DEMO_BOARD_URL: &str = "https://app.whiteboard.microsoft.com/me/whiteboards/demo";
116const DEMO_REPLACEMENT_LINK: &str = "https://demo.invalid/replacement";
117const DEMO_ROOM_THREAD: &str = "19:meeting_demo-room-1@thread.v2";
118
119pub enum DemoCall {
120 Test,
121 People(Vec<Person>),
122 Meeting {
123 guests: Vec<Person>,
124 lobby: bool,
125 organizer: bool,
126 },
127 Incoming(Person),
128}
129
130pub fn demo_guests(count: usize) -> Vec<Person> {
131 DEMO_GUESTS
132 .iter()
133 .take(count)
134 .enumerate()
135 .map(|(index, name)| (format!("8:orgid:demo-guest-{index}"), (*name).to_owned()))
136 .collect()
137}
138
139pub fn demo_caller() -> Person {
140 (DEMO_CALLER.0.to_owned(), DEMO_CALLER.1.to_owned())
141}
142
143pub fn demo_video_ring() -> IncomingRing {
144 IncomingRing {
145 video: true,
146 ..demo_ring()
147 }
148}
149
150pub fn demo_ring() -> IncomingRing {
151 let (mri, display_name) = demo_caller();
152 IncomingRing {
153 ring_id: DEMO_RING_ID,
154 caller: Caller { mri, display_name },
155 thread_id: Some("demo-chat-mara".to_owned()),
156 video: false,
157 is_group: false,
158 subject: None,
159 }
160}
161
162fn device(index: u16, name: &str) -> AudioDevice {
163 AudioDevice {
164 index,
165 guid: format!("demo-{index}"),
166 name: name.to_owned(),
167 }
168}
169
170fn demo_cameras() -> Vec<CameraDevice> {
171 vec![
172 CameraDevice {
173 key: "0".into(),
174 name: "Integrated Camera".into(),
175 },
176 CameraDevice {
177 key: "1".into(),
178 name: "Studio Webcam".into(),
179 },
180 ]
181}
182
183fn demo_share_sources() -> Vec<ShareSource> {
184 let window = |id: u64, title: &str| ShareSource {
185 id,
186 kind: ShareKind::Window,
187 title: title.to_owned(),
188 };
189 vec![
190 ShareSource {
191 id: 1,
192 kind: ShareKind::Screen,
193 title: String::new(),
194 },
195 window(2, "Release notes - Docs"),
196 window(3, "Standup board"),
197 window(4, "Terminal"),
198 ]
199}
200
201fn demo_devices() -> DeviceLists {
202 DeviceLists {
203 inputs: vec![
204 device(0, "Headset Microphone"),
205 device(1, "Built-in Microphone"),
206 ],
207 outputs: vec![device(0, "Headset"), device(1, "Speakers")],
208 }
209}
210
211pub fn start_demo_call(script: DemoCall) -> CallHandle {
212 start_demo_scene_call(script, DemoScene::Plain)
213}
214
215pub fn start_demo_scene_call(script: DemoCall, scene: DemoScene) -> CallHandle {
216 let (handle, control) = call_channel();
217 crate::runtime::handle().spawn(run_demo_call(control, script, scene));
218 handle
219}
220
221fn roster_of(people: &[Person]) -> Vec<RosterEntry> {
222 people
223 .iter()
224 .enumerate()
225 .map(|(index, (mri, name))| RosterEntry {
226 mri: mri.clone(),
227 display_name: name.clone(),
228 muted: index % 3 == 1,
229 in_lobby: false,
230 has_video: index < DEMO_CAMERAS,
231 sharing: false,
232 hand: None,
233 spotlight: None,
234 organizer: false,
235 })
236 .collect()
237}
238
239async fn run_demo_call(mut control: CallControl, script: DemoCall, scene: DemoScene) {
240 control.send(CallUpdate::OwnIdentity {
241 mri: DEMO_OWN_MRI.to_owned(),
242 });
243 let (people, lobby) = match &script {
244 DemoCall::Test => (vec![(ECHO_MRI.to_owned(), ECHO_NAME.to_owned())], false),
245 DemoCall::People(callees) => (callees.clone(), false),
246 DemoCall::Meeting { guests, lobby, .. } => (guests.clone(), *lobby),
247 DemoCall::Incoming(caller) => (vec![caller.clone()], false),
248 };
249 if !ring_until_answered(&mut control, &script).await {
250 control.send(CallUpdate::State(CallState::Ended {
251 reason: EndReason::Cancelled,
252 }));
253 return;
254 }
255 control.send(CallUpdate::ListenOnly(false));
256 control.send(CallUpdate::Devices(demo_devices()));
257 control.send(CallUpdate::Cameras(demo_cameras()));
258 control.send(CallUpdate::ShareSources(demo_share_sources()));
259 control.send(CallUpdate::Selected {
260 input: DeviceChoice::SystemDefault,
261 output: DeviceChoice::SystemDefault,
262 });
263 control.send(CallUpdate::State(CallState::Connected {
264 since: Instant::now(),
265 }));
266 if lobby {
267 control.send(CallUpdate::Lobby(true));
268 if control.until_hangup(sleep(LOBBY_WAIT)).await.is_err() {
269 end(&control, EndReason::LocalHangup);
270 return;
271 }
272 control.send(CallUpdate::Lobby(false));
273 }
274 let mut roster = roster_of(&people);
275 if matches!(script, DemoCall::People(_)) {
276 control.send(CallUpdate::ReplacementLink(
277 DEMO_REPLACEMENT_LINK.to_owned(),
278 ));
279 }
280 if matches!(
281 script,
282 DemoCall::Meeting {
283 organizer: true,
284 ..
285 }
286 ) {
287 roster.push(demo_organizer());
288 roster.extend(
289 DEMO_WAITING
290 .iter()
291 .enumerate()
292 .map(|(index, name)| demo_waiting(index, name)),
293 );
294 }
295 if matches!(script, DemoCall::Meeting { .. }) {
296 for (index, rank) in DEMO_FIRST_HANDS {
297 if let Some(entry) = roster.get_mut(index) {
298 entry.hand = Some(demo_hand(rank));
299 }
300 }
301 }
302 control.send(CallUpdate::Roster(roster.clone()));
303 let video = !matches!(script, DemoCall::Test);
304 let sharer = matches!(script, DemoCall::Meeting { .. })
305 .then(|| people.get(1).map(|person| person.0.clone()))
306 .flatten();
307 start_scene(&control, scene);
308 speak_until_hangup(control, people, roster, video, sharer, scene).await;
309}
310
311async fn ring_until_answered(control: &mut CallControl, script: &DemoCall) -> bool {
312 let steps: Vec<(Option<Progress>, Duration)> = match script {
313 DemoCall::People(_) => vec![
314 (Some(Progress::Calling), RING_START),
315 (Some(Progress::Ringing), ANSWER_DELAY - RING_START),
316 ],
317 DemoCall::Incoming(_) => vec![(None, INCOMING_CONNECT_DELAY)],
318 DemoCall::Test | DemoCall::Meeting { .. } => vec![(None, CONNECT_DELAY)],
319 };
320 for (progress, wait) in steps {
321 if let Some(progress) = progress {
322 control.send(CallUpdate::Progress(progress));
323 }
324 if control.until_hangup(sleep(wait)).await.is_err() {
325 return false;
326 }
327 }
328 true
329}
330
331fn publish_demo_video(
332 control: &CallControl,
333 people: &[Person],
334 tick: u32,
335 sharing: bool,
336 sharer: Option<&str>,
337 camera: Option<bool>,
338) {
339 if let Some(blur) = camera {
340 control.video.publish(
341 VideoKey::LocalCamera,
342 self_view((tick + SELF_PHASE) as usize, blur),
343 );
344 }
345 for (index, (mri, _)) in people.iter().take(DEMO_CAMERAS).enumerate() {
346 let frame = pattern_frame(PatternKind::Camera, tick + index as u32 * GUEST_PHASE);
347 control
348 .video
349 .publish(VideoKey::Person(mri.clone()), bgra_from_i420(frame));
350 }
351 if sharing && sharer.is_some() && tick.is_multiple_of(SCREEN_EVERY_TICKS) {
352 control.video.publish(
353 VideoKey::Screen,
354 bgra_from_i420(pattern_frame(PatternKind::Screen, tick)),
355 );
356 }
357}
358
359fn start_scene(control: &CallControl, scene: DemoScene) {
360 match scene {
361 DemoScene::Recording => control.send(CallUpdate::Recording(true)),
362 DemoScene::Consent => {
363 control.send(CallUpdate::Recording(true));
364 control.send(CallUpdate::ConsentRequired(true));
365 }
366 DemoScene::Hold => control.send(CallUpdate::Hold(HoldState::Local)),
367 DemoScene::Held => control.send(CallUpdate::Hold(HoldState::Remote)),
368 DemoScene::Network => control.send(CallUpdate::Health(poor_network_health())),
369 DemoScene::Call | DemoScene::Breakout | DemoScene::Whiteboard | DemoScene::Plain => {}
370 }
371}
372
373fn poor_network_health() -> CallHealth {
374 CallHealth {
375 level: NetworkLevel::Poor,
376 cpu_limited: false,
377 sample: HealthSample {
378 loss_percent: 7.2,
379 round_trip_ms: 310.,
380 jitter_ms: 38.,
381 sent_kbps: 420.,
382 received_kbps: 1180.,
383 limitation: Limitation::Bandwidth,
384 },
385 transport: TransportDetails {
386 dtls_state: "Connected".to_owned(),
387 tls_version: "FEFD".to_owned(),
388 dtls_cipher: "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256".to_owned(),
389 srtp_cipher: "AEAD_AES_128_GCM".to_owned(),
390 local_fingerprint: String::new(),
391 remote_fingerprint: String::new(),
392 },
393 path: MediaPath::Direct,
394 }
395}
396
397fn scene_tick(control: &CallControl, scene: DemoScene, ticks: u32, people: &[Person]) {
398 match scene {
399 DemoScene::Breakout if ticks == BREAKOUT_AT_TICKS => {
400 control.send(CallUpdate::BreakoutMove(BreakoutMove {
401 room_name: "Room 1".to_owned(),
402 target: MeetingTarget {
403 thread_id: DEMO_ROOM_THREAD.to_owned(),
404 tenant_id: "demo-tenant".to_owned(),
405 organizer_id: "demo-me".to_owned(),
406 meeting_data: None,
407 },
408 returning: false,
409 }))
410 }
411 DemoScene::Whiteboard if ticks == WHITEBOARD_AT_TICKS => {
412 control.send(CallUpdate::Whiteboard(Some(ContentShare {
413 session_id: "demo-whiteboard".to_owned(),
414 presenter: people.first().map(|person| person.0.clone()),
415 subject: "Whiteboard".to_owned(),
416 url: Some(DEMO_BOARD_URL.to_owned()),
417 whiteboard: true,
418 })))
419 }
420 _ => {}
421 }
422}
423
424async fn speak_until_hangup(
425 mut control: CallControl,
426 people: Vec<Person>,
427 mut roster: Vec<RosterEntry>,
428 video: bool,
429 sharer: Option<String>,
430 scene: DemoScene,
431) {
432 let started = Instant::now();
433 let mut video_ticks = 0u32;
434 let mut sharing = false;
435 let mut camera_on = false;
436 let mut incoming_video = true;
437 let mut blur = false;
438 let mut captions_on = false;
439 let mut caption_ticks = 0usize;
440 let mut video_tick = interval(VIDEO_PERIOD);
441 let mut muted = false;
442 let mut input = DeviceChoice::SystemDefault;
443 let mut output = DeviceChoice::SystemDefault;
444 let mut ticks = 0u32;
445 let mut share_sound = false;
446 let mut tick = interval(LEVEL_PERIOD);
447 loop {
448 tokio::select! {
449 _ = video_tick.tick(), if video || camera_on => {
450 let elapsed = started.elapsed();
451 let share_now = sharer.is_some() && (SHARE_START..SHARE_END).contains(&elapsed);
452 if share_now != sharing {
453 sharing = share_now;
454 control.send(CallUpdate::ScreenShare(sharer.clone().filter(|_| sharing)));
455 }
456 publish_demo_video(&control, if incoming_video { people.as_slice() } else { &[] }, video_ticks, sharing, sharer.as_deref(), camera_on.then_some(blur));
457 video_ticks += 1;
458 }
459 _ = tick.tick() => {
460 let phase = ticks % CYCLE_TICKS;
461 let remote_speaks = REMOTE_SPEAKS.contains(&phase);
462 control.send(CallUpdate::Levels {
463 local: if LOCAL_SPEAKS.contains(&phase) && !muted { SPEAKING_LEVEL } else { 0.0 },
464 remote: if remote_speaks { SPEAKING_LEVEL } else { 0.0 },
465 });
466 if people.len() > 1 && ticks.is_multiple_of(SPEAKER_TICKS) {
467 let speaker = &people[(ticks / SPEAKER_TICKS) as usize % people.len()];
468 control.send(CallUpdate::Speakers(vec![speaker.0.clone()]));
469 }
470 if ticks % REACTION_EVERY_TICKS == REACTION_EVERY_TICKS / 2
471 && let Some((mri, _)) = people.get((ticks / REACTION_EVERY_TICKS) as usize % people.len().max(1))
472 {
473 let reaction = Reaction::ALL[(ticks / REACTION_EVERY_TICKS) as usize % Reaction::ALL.len()];
474 control.send(CallUpdate::Reaction { mri: mri.clone(), reaction });
475 }
476 if captions_on {
477 if let Some(entry) = demo_caption(&people, caption_ticks) {
478 control.send(CallUpdate::Caption(entry));
479 }
480 caption_ticks += 1;
481 }
482 scene_tick(&control, scene, ticks, &people);
483 ticks += 1;
484 }
485 command = control.recv() => match command {
486 Some(CallCommand::Mute(command)) => {
487 muted = command.target(muted);
488 control.send(CallUpdate::Muted(muted));
489 }
490 Some(CallCommand::SelectInput(choice)) => {
491 input = choice;
492 control.send(CallUpdate::Selected { input: input.clone(), output: output.clone() });
493 }
494 Some(CallCommand::SelectOutput(choice)) => {
495 output = choice;
496 control.send(CallUpdate::Selected { input: input.clone(), output: output.clone() });
497 }
498 Some(CallCommand::RefreshDevices) => control.send(CallUpdate::Devices(demo_devices())),
499 Some(CallCommand::SetCamera(on)) => {
500 camera_on = on;
501 control.send(CallUpdate::Camera(on));
502 }
503 Some(CallCommand::SelectCamera(_)) => {}
504 Some(CallCommand::StartShare(source)) => {
505 control.send(CallUpdate::LocalShare(Some(source.label())));
506 if share_sound {
507 control.send(CallUpdate::ShareSound(true));
508 }
509 }
510 Some(CallCommand::StopShare) => control.send(CallUpdate::LocalShare(None)),
511 Some(CallCommand::SetShareSound(on)) => share_sound = on,
512 Some(CallCommand::SetHand(raised)) => {
513 set_demo_hand(&mut roster, DEMO_OWN_MRI, raised);
514 control.send(CallUpdate::Roster(roster.clone()));
515 }
516 Some(CallCommand::LowerHand { mri }) => {
517 set_demo_hand(&mut roster, &mri, false);
518 control.send(CallUpdate::Roster(roster.clone()));
519 }
520 Some(CallCommand::LowerAllHands) => {
521 roster.iter_mut().for_each(|entry| entry.hand = None);
522 control.send(CallUpdate::Roster(roster.clone()));
523 }
524 Some(CallCommand::SendReaction(reaction)) => {
525 control.send(CallUpdate::Reaction { mri: DEMO_OWN_MRI.to_owned(), reaction });
526 }
527 Some(CallCommand::Admit { mri }) => {
528 roster.iter_mut().filter(|entry| entry.mri == mri).for_each(|entry| entry.in_lobby = false);
529 control.send(CallUpdate::Roster(roster.clone()));
530 }
531 Some(CallCommand::AdmitAll) => {
532 roster.iter_mut().for_each(|entry| entry.in_lobby = false);
533 control.send(CallUpdate::Roster(roster.clone()));
534 }
535 Some(CallCommand::Deny { mri } | CallCommand::RemoveParticipant { mri }) => {
536 roster.retain(|entry| entry.mri != mri);
537 control.send(CallUpdate::Roster(roster.clone()));
538 }
539 Some(CallCommand::MuteParticipant { mri }) => {
540 roster.iter_mut().filter(|entry| entry.mri == mri).for_each(|entry| entry.muted = true);
541 control.send(CallUpdate::Roster(roster.clone()));
542 }
543 Some(CallCommand::MuteAll) => {
544 roster.iter_mut().filter(|entry| entry.mri != DEMO_OWN_MRI).for_each(|entry| entry.muted = true);
545 control.send(CallUpdate::Roster(roster.clone()));
546 }
547 Some(CallCommand::Spotlight { mri }) => {
548 let rank = roster.iter().filter_map(|entry| entry.spotlight.as_ref().map(|state| state.rank)).max().unwrap_or(0) + 1;
549 if let Some(entry) = roster.iter_mut().find(|entry| entry.mri == mri) {
550 entry.spotlight = Some(demo_spotlight(rank));
551 }
552 control.send(CallUpdate::Roster(roster.clone()));
553 }
554 Some(CallCommand::StopSpotlight { mri }) => {
555 roster.iter_mut().filter(|entry| entry.mri == mri).for_each(|entry| entry.spotlight = None);
556 control.send(CallUpdate::Roster(roster.clone()));
557 }
558 Some(CallCommand::SetCaptions(on)) => {
559 captions_on = on;
560 caption_ticks = 0;
561 control.send(CallUpdate::Captions(if on { CaptionState::On } else { CaptionState::Off }));
562 }
563 Some(CallCommand::SetBackground(choice)) => blur = choice != BackgroundChoice::None,
564 Some(CallCommand::SetIncomingVideo(enabled)) => {
565 incoming_video = enabled;
566 people.iter().for_each(|(mri, _)| control.video.forget(&VideoKey::Person(mri.clone())));
567 control.send(CallUpdate::IncomingVideo(enabled));
568 }
569 Some(CallCommand::SetRecording { on, .. }) => control.send(CallUpdate::Recording(on)),
570 Some(CallCommand::ConsentToRecording) => control.send(CallUpdate::ConsentRequired(false)),
571 Some(CallCommand::Hold(hold)) => control.send(CallUpdate::Hold(if hold { HoldState::Local } else { HoldState::Active })),
572 Some(CallCommand::Transfer { .. }) => {
573 control.send(CallUpdate::Notice("Call transferred".to_owned()));
574 end(&control, EndReason::LocalHangup);
575 return;
576 }
577 Some(CallCommand::OpenWhiteboard { .. }) => control.send(CallUpdate::WhiteboardUrl(DEMO_BOARD_URL.to_owned())),
578 Some(CallCommand::RefreshShareSources) => control.send(CallUpdate::ShareSources(demo_share_sources())),
579 Some(CallCommand::Hangup | CallCommand::EndMeeting) | None => {
580 end(&control, EndReason::LocalHangup);
581 return;
582 }
583 },
584 }
585 }
586}
587
588fn demo_organizer() -> RosterEntry {
589 RosterEntry {
590 mri: DEMO_OWN_MRI.to_owned(),
591 display_name: "You".to_owned(),
592 muted: false,
593 in_lobby: false,
594 has_video: false,
595 sharing: false,
596 hand: None,
597 spotlight: None,
598 organizer: true,
599 }
600}
601
602fn demo_waiting(index: usize, name: &str) -> RosterEntry {
603 RosterEntry {
604 mri: format!("8:orgid:demo-waiting-{index}"),
605 display_name: name.to_owned(),
606 muted: false,
607 in_lobby: true,
608 has_video: false,
609 sharing: false,
610 hand: None,
611 spotlight: None,
612 organizer: false,
613 }
614}
615
616fn demo_spotlight(rank: u64) -> PublishedState {
617 PublishedState {
618 state_id: format!("demo-spotlight-{rank}"),
619 rank,
620 }
621}
622
623fn demo_caption(people: &[Person], tick: usize) -> Option<CaptionEntry> {
624 let line = tick / (CAPTION_HOLD_TICKS * 2) % DEMO_CAPTIONS.len();
625 let within = tick % (CAPTION_HOLD_TICKS * 2);
626 let (speaker, text) = DEMO_CAPTIONS[line];
627 let words: Vec<&str> = text.split(' ').collect();
628 let shown = ((within + 1) * CAPTION_WORDS_PER_TICK).min(words.len());
629 let (mri, name) = people.get(speaker % people.len().max(1))?;
630 Some(CaptionEntry {
631 id: format!("demo-caption-{}", tick / (CAPTION_HOLD_TICKS * 2)),
632 user_id: mri.clone(),
633 display_name: name.clone(),
634 text: words[..shown].join(" "),
635 is_final: shown == words.len(),
636 })
637}
638
639fn demo_hand(rank: u64) -> RaisedHand {
640 RaisedHand {
641 state_id: format!("demo-hand-{rank}"),
642 rank,
643 }
644}
645
646fn set_demo_hand(roster: &mut Vec<RosterEntry>, mri: &str, raised: bool) {
647 let next_rank = roster
648 .iter()
649 .filter_map(|entry| entry.hand.as_ref().map(|hand| hand.rank))
650 .max()
651 .unwrap_or(0)
652 + 1;
653 if !raised {
654 if let Some(entry) = roster.iter_mut().find(|entry| entry.mri == mri) {
655 entry.hand = None;
656 }
657 roster.retain(|entry| entry.mri != DEMO_OWN_MRI || entry.hand.is_some());
658 return;
659 }
660 match roster.iter_mut().find(|entry| entry.mri == mri) {
661 Some(entry) => entry.hand = Some(demo_hand(next_rank)),
662 None => roster.push(RosterEntry {
663 mri: mri.to_owned(),
664 display_name: "You".to_owned(),
665 muted: false,
666 in_lobby: false,
667 has_video: false,
668 sharing: false,
669 hand: Some(demo_hand(next_rank)),
670 spotlight: None,
671 organizer: false,
672 }),
673 }
674}
675
676fn end(control: &CallControl, reason: EndReason) {
677 control.send(CallUpdate::State(CallState::Ended { reason }));
678}
679
680#[cfg(test)]
681mod tests {
682 use super::*;
683
684 #[test]
685 fn demo_guests_have_distinct_mris_and_names() {
686 let guests = demo_guests(11);
687 assert_eq!(guests.len(), 11);
688 let mut mris: Vec<&String> = guests.iter().map(|guest| &guest.0).collect();
689 mris.sort();
690 mris.dedup();
691 assert_eq!(mris.len(), 11);
692 }
693
694 #[test]
695 fn demo_hands_queue_in_order_and_lowering_drops_the_own_entry() {
696 let mut roster = roster_of(&demo_guests(3));
697 set_demo_hand(&mut roster, "8:orgid:demo-guest-1", true);
698 set_demo_hand(&mut roster, DEMO_OWN_MRI, true);
699 let ranks: Vec<u64> = roster
700 .iter()
701 .filter_map(|entry| entry.hand.as_ref().map(|hand| hand.rank))
702 .collect();
703 assert_eq!(ranks, vec![1, 2]);
704 set_demo_hand(&mut roster, DEMO_OWN_MRI, false);
705 assert!(roster.iter().all(|entry| entry.mri != DEMO_OWN_MRI));
706 }
707
708 #[test]
709 fn the_demo_ring_names_a_caller_and_a_chat() {
710 let ring = demo_ring();
711 assert_eq!(ring.caller.display_name, "Mara Lindqvist");
712 assert_eq!(ring.thread_id.as_deref(), Some("demo-chat-mara"));
713 }
714}