BlueGit

ict rusty-teams

Files

rusty-teams / crates / calling / src / video_layout.rs

video_layout.rs

video_layout.rs 28.9 KiB Download Raw
1use std::collections::HashMap;
2use std::sync::{Arc, Mutex};
3
4use libwebrtc::MediaType;
5use libwebrtc::peer_connection::PeerConnection;
6use libwebrtc::peer_connection_factory::PeerConnectionFactory;
7use libwebrtc::rtp_parameters::{RtpCodecCapability, RtpEncodingParameters};
8use libwebrtc::rtp_transceiver::{RtpTransceiver, RtpTransceiverDirection, RtpTransceiverInit};
9use serde_json::{Value, json};
10
11use crate::error::{Error, Result};
12use crate::sdp::{LineRole, OfferPlan, StreamLine};
13use crate::send_control::capture_macroblocks;
14use crate::video_frame::VideoKey;
15use crate::video_quality::VideoQuality;
16
17pub const RECEIVE_SLOTS: usize = 9;
18pub const CAMERA_MID: &str = "1";
19pub const SHARE_MID: &str = "11";
20pub const ONE_TO_ONE_SHARE_MID: &str = "2";
21
22const CAMERA_LINE_LABEL: &str = "main-video";
23const SHARE_LINE_LABEL: &str = "applicationsharing-video";
24const CAMERA_STREAM: &str = "camera";
25pub const SCREEN_STREAM: &str = "screen";
26const H264: &str = "video/h264";
27const RTX: &str = "video/rtx";
28const NO_SOURCE: i64 = -1;
29const STAGE_720_REQUEST: ReceiveLimits = ReceiveLimits {
30 max_fs: 3600,
31 max_fps: 3000,
32 max_mbps: 108_000,
33};
34/// 1080p @ 30: max-fs 8160 macroblocks, mbps ≈ 8160 * 30.
35const STAGE_1080_REQUEST: ReceiveLimits = ReceiveLimits {
36 max_fs: 8160,
37 max_fps: 3000,
38 max_mbps: 244_800,
39};
40const SMALL_REQUEST: ReceiveLimits = ReceiveLimits {
41 max_fs: 920,
42 max_fps: 3000,
43 max_mbps: 27_600,
44};
45const SCREEN_REQUEST: ReceiveLimits = ReceiveLimits {
46 max_fs: 8160,
47 max_fps: 1500,
48 max_mbps: 135_000,
49};
50const SUBSCRIBE_PROFILE: &str = "64001f";
51const SIMULCAST_RIDS: [&str; 3] = ["1", "2", "3"];
52const SIMULCAST_START_SCALES: [f64; 3] = [4.0, 2.0, 1.0];
53const SIMULCAST_SCALABILITY: &str = "L1T1";
54const THREE_LAYER_MIN_FS: u32 = 2040;
55const SEND_CAPABILITY_FPS: u32 = 30;
56
57#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
58pub enum TileDetail {
59 #[default]
60 Stage,
61 Small,
62}
63
64impl TileDetail {
65 fn limits(self, quality: VideoQuality) -> ReceiveLimits {
66 match self {
67 TileDetail::Stage => match quality {
68 VideoQuality::P720 => STAGE_720_REQUEST,
69 VideoQuality::Auto | VideoQuality::P1080 => STAGE_1080_REQUEST,
70 },
71 TileDetail::Small => SMALL_REQUEST,
72 }
73 }
74}
75
76#[derive(Debug, Clone, PartialEq, Eq)]
77pub struct VideoWant {
78 pub mri: String,
79 pub detail: TileDetail,
80}
81
82#[derive(Debug, Clone, Copy, PartialEq, Eq)]
83struct ReceiveLimits {
84 max_fs: u32,
85 max_fps: u32,
86 max_mbps: u32,
87}
88
89pub fn offer_plan() -> OfferPlan {
90 OfferPlan {
91 screen_share_mids: vec![SHARE_MID.to_owned()],
92 gallery_mids: Vec::new(),
93 fold_groups: Vec::new(),
94 }
95}
96
97pub fn one_to_one_plan() -> OfferPlan {
98 OfferPlan {
99 screen_share_mids: vec![ONE_TO_ONE_SHARE_MID.to_owned()],
100 gallery_mids: Vec::new(),
101 fold_groups: Vec::new(),
102 }
103}
104
105/// Offered after the audio line: camera, `RECEIVE_SLOTS` receive-only slots, screen share (mids 1, 2-10, 11).
106#[derive(Clone)]
107pub struct VideoLines {
108 pub camera: RtpTransceiver,
109 pub share: Option<RtpTransceiver>,
110}
111
112fn h264_only(capabilities: Vec<RtpCodecCapability>) -> Vec<RtpCodecCapability> {
113 capabilities
114 .into_iter()
115 .filter(|codec| {
116 let mime = codec.mime_type.to_ascii_lowercase();
117 mime == H264 || mime == RTX
118 })
119 .collect()
120}
121
122fn add_line(
123 peer: &PeerConnection,
124 direction: RtpTransceiverDirection,
125 stream: Option<&str>,
126 codecs: Vec<RtpCodecCapability>,
127 send_encodings: Vec<RtpEncodingParameters>,
128) -> Result<RtpTransceiver> {
129 let init = RtpTransceiverInit {
130 direction,
131 stream_ids: stream.map(str::to_owned).into_iter().collect(),
132 send_encodings,
133 };
134 let transceiver = peer
135 .add_transceiver_for_media(MediaType::Video, init)
136 .map_err(|error| Error::Webrtc(error.to_string()))?;
137 transceiver
138 .set_codec_preferences(codecs)
139 .map_err(|error| Error::Webrtc(error.to_string()))?;
140 Ok(transceiver)
141}
142
143fn simulcast_encodings() -> Vec<RtpEncodingParameters> {
144 SIMULCAST_RIDS
145 .iter()
146 .zip(SIMULCAST_START_SCALES)
147 .map(|(rid, scale)| RtpEncodingParameters {
148 rid: (*rid).to_owned(),
149 scale_resolution_down_by: Some(scale),
150 scalability_mode: Some(SIMULCAST_SCALABILITY.to_owned()),
151 ..RtpEncodingParameters::default()
152 })
153 .collect()
154}
155
156pub fn add_video_lines(
157 peer: &PeerConnection,
158 factory: &PeerConnectionFactory,
159) -> Result<VideoLines> {
160 let sending = h264_only(factory.get_rtp_sender_capabilities(MediaType::Video).codecs);
161 let receiving = h264_only(
162 factory
163 .get_rtp_receiver_capabilities(MediaType::Video)
164 .codecs,
165 );
166 let camera = add_line(
167 peer,
168 RtpTransceiverDirection::SendRecv,
169 Some(CAMERA_STREAM),
170 sending.clone(),
171 simulcast_encodings(),
172 )?;
173 for _ in 0..RECEIVE_SLOTS {
174 add_line(
175 peer,
176 RtpTransceiverDirection::RecvOnly,
177 None,
178 receiving.clone(),
179 Vec::new(),
180 )?;
181 }
182 let share = add_line(
183 peer,
184 RtpTransceiverDirection::SendRecv,
185 Some(SCREEN_STREAM),
186 sending,
187 Vec::new(),
188 )?;
189 Ok(VideoLines {
190 camera,
191 share: Some(share),
192 })
193}
194
195/// A sharing line added to a running direct call, the way Teams adds it before its share offer.
196pub fn add_share_line(
197 peer: &PeerConnection,
198 factory: &PeerConnectionFactory,
199) -> Result<RtpTransceiver> {
200 let sending = h264_only(factory.get_rtp_sender_capabilities(MediaType::Video).codecs);
201 add_line(
202 peer,
203 RtpTransceiverDirection::SendRecv,
204 Some(SCREEN_STREAM),
205 sending,
206 Vec::new(),
207 )
208}
209
210pub fn add_one_to_one_lines(
211 peer: &PeerConnection,
212 factory: &PeerConnectionFactory,
213) -> Result<VideoLines> {
214 let sending = h264_only(factory.get_rtp_sender_capabilities(MediaType::Video).codecs);
215 let camera = add_line(
216 peer,
217 RtpTransceiverDirection::SendRecv,
218 Some(CAMERA_STREAM),
219 sending.clone(),
220 Vec::new(),
221 )?;
222 let share = add_line(
223 peer,
224 RtpTransceiverDirection::SendRecv,
225 Some(SCREEN_STREAM),
226 sending,
227 Vec::new(),
228 )?;
229 Ok(VideoLines {
230 camera,
231 share: Some(share),
232 })
233}
234
235/// Per-line direction told to the mixer through `updateMediaDescriptions`; no SDP renegotiation.
236#[derive(Debug, Clone, PartialEq, Eq)]
237pub struct MediaDescription {
238 pub mid: String,
239 pub direction: &'static str,
240 pub label: Option<&'static str>,
241}
242
243impl MediaDescription {
244 pub fn camera(sending: bool) -> Self {
245 Self::camera_line(CAMERA_MID, sending)
246 }
247
248 pub fn share(sending: bool) -> Self {
249 Self::share_line(SHARE_MID, sending)
250 }
251
252 pub fn camera_line(mid: impl Into<String>, sending: bool) -> Self {
253 Self::line(mid.into(), sending, CAMERA_LINE_LABEL)
254 }
255
256 pub fn share_line(mid: impl Into<String>, sending: bool) -> Self {
257 Self::line(mid.into(), sending, SHARE_LINE_LABEL)
258 }
259
260 fn line(mid: String, sending: bool, label: &'static str) -> Self {
261 if sending {
262 MediaDescription {
263 mid,
264 direction: "sendrecv",
265 label: Some(label),
266 }
267 } else {
268 MediaDescription {
269 mid,
270 direction: "recvonly",
271 label: None,
272 }
273 }
274 }
275
276 pub fn wire(&self) -> Value {
277 let mut description = json!({"mid": self.mid, "direction": self.direction});
278 if let Some(label) = self.label {
279 description["label"] = json!(label);
280 }
281 description
282 }
283}
284
285#[derive(Debug, Clone, PartialEq, Eq)]
286pub struct ReceiveSlot {
287 pub mid: String,
288 pub stream_id: u32,
289}
290
291#[derive(Debug, Clone, Default, PartialEq, Eq)]
292pub struct SlotTable {
293 pub people: Vec<ReceiveSlot>,
294 pub screen: Option<ReceiveSlot>,
295}
296
297impl SlotTable {
298 pub fn from_streams(streams: &[StreamLine]) -> Self {
299 let slot = |stream: &StreamLine| {
300 Some(ReceiveSlot {
301 mid: stream.browser_mid.clone(),
302 stream_id: stream.source_stream_id?,
303 })
304 };
305 let people = streams
306 .iter()
307 .filter(|stream| stream.role == LineRole::MainVideo)
308 .skip(1)
309 .filter_map(slot)
310 .take(RECEIVE_SLOTS)
311 .collect();
312 let screen = streams
313 .iter()
314 .find(|stream| stream.role == LineRole::ScreenShare)
315 .and_then(slot);
316 SlotTable { people, screen }
317 }
318
319 pub fn is_empty(&self) -> bool {
320 self.people.is_empty() && self.screen.is_none()
321 }
322}
323
324#[derive(Debug, Clone, PartialEq, Eq)]
325pub struct Assignment {
326 pub mri: String,
327 pub source: u32,
328 pub detail: TileDetail,
329}
330
331impl Assignment {
332 fn same_source(&self, other: &Assignment) -> bool {
333 self.mri == other.mri && self.source == other.source
334 }
335}
336
337pub fn plan_receive(
338 current: &[Option<Assignment>],
339 candidates: &[Assignment],
340) -> Vec<Option<Assignment>> {
341 let wanted: Vec<&Assignment> = candidates.iter().take(current.len()).collect();
342 let mut next: Vec<Option<Assignment>> = current
343 .iter()
344 .map(|slot| {
345 let held = slot.as_ref()?;
346 wanted
347 .iter()
348 .find(|assignment| assignment.same_source(held))
349 .map(|assignment| (*assignment).clone())
350 })
351 .collect();
352 for assignment in wanted {
353 if next
354 .iter()
355 .flatten()
356 .any(|held| held.same_source(assignment))
357 {
358 continue;
359 }
360 if let Some(free) = next.iter_mut().find(|slot| slot.is_none()) {
361 *free = Some(assignment.clone());
362 }
363 }
364 next
365}
366
367pub fn prioritize(
368 candidates: Vec<(String, u32)>,
369 speaker_history: &[String],
370 wants: Option<&[VideoWant]>,
371) -> Vec<Assignment> {
372 if let Some(wants) = wants {
373 return wants
374 .iter()
375 .filter_map(|want| {
376 let (mri, source) = candidates.iter().find(|(mri, _)| *mri == want.mri)?;
377 Some(Assignment {
378 mri: mri.clone(),
379 source: *source,
380 detail: want.detail,
381 })
382 })
383 .collect();
384 }
385 let rank = |mri: &str| {
386 speaker_history
387 .iter()
388 .position(|speaker| speaker == mri)
389 .unwrap_or(usize::MAX)
390 };
391 let mut ordered: Vec<Assignment> = candidates
392 .into_iter()
393 .map(|(mri, source)| Assignment {
394 mri,
395 source,
396 detail: TileDetail::Stage,
397 })
398 .collect();
399 ordered.sort_by_key(|assignment| rank(&assignment.mri));
400 ordered
401}
402
403#[derive(Debug, Clone, PartialEq, Eq)]
404pub struct SourceRequest {
405 pub mid: String,
406 pub stream_id: u32,
407 pub source: Option<u32>,
408 pub screen: bool,
409 pub detail: TileDetail,
410 pub quality: VideoQuality,
411}
412
413pub fn requests_for(
414 current: &[Option<Assignment>],
415 next: &[Option<Assignment>],
416 slots: &[ReceiveSlot],
417 quality: VideoQuality,
418) -> Vec<SourceRequest> {
419 slots
420 .iter()
421 .zip(current.iter().zip(next))
422 .filter(|(_, (before, after))| before != after)
423 .map(|(slot, (_, after))| SourceRequest {
424 mid: slot.mid.clone(),
425 stream_id: slot.stream_id,
426 source: after.as_ref().map(|assignment| assignment.source),
427 screen: false,
428 detail: after
429 .as_ref()
430 .map(|assignment| assignment.detail)
431 .unwrap_or_default(),
432 quality,
433 })
434 .collect()
435}
436
437impl SourceRequest {
438 /// Body of the `applyChannelParameters` link, the signaling twin of the data-channel `sr` message.
439 pub fn body(&self, sequence_number: u64) -> Value {
440 let limits = if self.screen {
441 SCREEN_REQUEST
442 } else {
443 self.detail.limits(self.quality)
444 };
445 let control = json!({
446 "controlVideoStreaming": {
447 "sequenceNumber": sequence_number,
448 "controlInfo": {
449 "sourceId": self.source.map_or(NO_SOURCE, i64::from),
450 "streamMsid": self.stream_id,
451 "fmtParams": [{
452 "max-fs": limits.max_fs,
453 "max-mbps": limits.max_mbps,
454 "max-fps": limits.max_fps,
455 "profile-level-id": SUBSCRIBE_PROFILE,
456 }],
457 },
458 },
459 });
460 json!({
461 "applyChannelParameters": {
462 "multiChannelParameter": {
463 "mids": [self.mid],
464 "mediaParameter": control.to_string(),
465 },
466 },
467 })
468 }
469}
470
471pub fn send_capabilities_body(
472 width: u32,
473 height: u32,
474 sequence_number: u64,
475 quality: VideoQuality,
476) -> Value {
477 send_capabilities_body_for(CAMERA_MID, width, height, sequence_number, quality)
478}
479
480pub fn send_capabilities_body_for(
481 camera_mid: &str,
482 width: u32,
483 height: u32,
484 sequence_number: u64,
485 quality: VideoQuality,
486) -> Value {
487 let ceiling = quality.capture_height().max(quality.capture_width());
488 let width = width.min(ceiling);
489 let height = height.min(ceiling);
490 let largest_side = width.max(height);
491 let layers = if capture_macroblocks(width, height) < THREE_LAYER_MIN_FS {
492 2
493 } else {
494 SIMULCAST_RIDS.len()
495 };
496 let capabilities = json!({
497 "maxVideoSendCapabilities": {
498 "max-width": largest_side,
499 "max-height": largest_side,
500 "max-fps": SEND_CAPABILITY_FPS,
501 "max-streams": SIMULCAST_RIDS.len(),
502 "max-layers": layers,
503 "sequence-number": sequence_number,
504 },
505 });
506 json!({
507 "applyChannelParameters": {
508 "multiChannelParameter": {
509 "mids": [camera_mid],
510 "mediaParameter": capabilities.to_string(),
511 },
512 },
513 })
514}
515
516/// Builds a send-capability body only when the camera size differs from the last one reported.
517#[derive(Debug, Default)]
518pub struct SendCapabilityReporter {
519 last_size: Option<(u32, u32)>,
520 last_quality: Option<VideoQuality>,
521 sequence_number: u64,
522}
523
524impl SendCapabilityReporter {
525 pub fn body_for(&mut self, size: (u32, u32), quality: VideoQuality) -> Option<Value> {
526 self.body_for_mid(CAMERA_MID, size, quality)
527 }
528
529 pub fn body_for_mid(
530 &mut self,
531 camera_mid: &str,
532 size: (u32, u32),
533 quality: VideoQuality,
534 ) -> Option<Value> {
535 if self.last_size == Some(size) && self.last_quality == Some(quality) {
536 return None;
537 }
538 self.last_size.replace(size);
539 self.last_quality.replace(quality);
540 self.sequence_number += 1;
541 Some(send_capabilities_body_for(
542 camera_mid,
543 size.0,
544 size.1,
545 self.sequence_number,
546 quality,
547 ))
548 }
549}
550
551#[derive(Clone, Default)]
552pub struct VideoRouter {
553 keys: Arc<Mutex<HashMap<String, VideoKey>>>,
554}
555
556impl VideoRouter {
557 pub fn set(&self, mid: &str, key: Option<VideoKey>) {
558 let mut keys = self.keys.lock().expect("router lock");
559 match key {
560 Some(key) => keys.insert(mid.to_owned(), key),
561 None => keys.remove(mid),
562 };
563 }
564
565 pub fn key_for(&self, mid: &str) -> Option<VideoKey> {
566 self.keys.lock().expect("router lock").get(mid).cloned()
567 }
568}
569
570#[cfg(test)]
571mod tests {
572 use super::*;
573
574 fn assignment(name: &str, source: u32) -> Assignment {
575 Assignment {
576 mri: format!("8:orgid:{name}"),
577 source,
578 detail: TileDetail::Stage,
579 }
580 }
581
582 fn stream(mid: &str, role: LineRole, id: Option<u32>) -> StreamLine {
583 StreamLine {
584 mid: mid.into(),
585 browser_mid: mid.into(),
586 role,
587 source_stream_id: id,
588 }
589 }
590
591 #[test]
592 fn slots_are_the_main_video_lines_after_the_camera_line() {
593 let streams = vec![
594 stream("0", LineRole::MainAudio, Some(201)),
595 stream("1", LineRole::MainVideo, Some(202)),
596 stream("2", LineRole::MainVideo, Some(203)),
597 stream("3", LineRole::MainVideo, Some(204)),
598 stream("4", LineRole::MainVideo, None),
599 stream("5", LineRole::MainVideo, Some(206)),
600 stream("11", LineRole::ScreenShare, Some(207)),
601 ];
602 let table = SlotTable::from_streams(&streams);
603 let mids: Vec<&str> = table.people.iter().map(|slot| slot.mid.as_str()).collect();
604 assert_eq!(mids, vec!["2", "3", "5"]);
605 assert_eq!(
606 table.screen,
607 Some(ReceiveSlot {
608 mid: "11".into(),
609 stream_id: 207
610 })
611 );
612 }
613
614 #[test]
615 fn nobody_is_dropped_while_they_are_still_wanted() {
616 let held = vec![
617 Some(assignment("a", 1)),
618 Some(assignment("b", 2)),
619 None,
620 None,
621 ];
622 let candidates = vec![assignment("c", 3), assignment("a", 1), assignment("b", 2)];
623 let next = plan_receive(&held, &candidates);
624 assert_eq!(next[0], Some(assignment("a", 1)));
625 assert_eq!(next[1], Some(assignment("b", 2)));
626 assert_eq!(next[2], Some(assignment("c", 3)));
627 assert_eq!(next[3], None);
628 }
629
630 #[test]
631 fn a_new_speaker_replaces_the_least_recent_person() {
632 let held: Vec<Option<Assignment>> = (1..=4)
633 .map(|index| Some(assignment(&format!("p{index}"), index)))
634 .collect();
635 let history = vec![
636 "8:orgid:p5".to_owned(),
637 "8:orgid:p1".to_owned(),
638 "8:orgid:p2".to_owned(),
639 "8:orgid:p3".to_owned(),
640 ];
641 let roster = (1..=5)
642 .map(|index| (format!("8:orgid:p{index}"), index))
643 .collect();
644 let next = plan_receive(&held, &prioritize(roster, &history, None));
645 let names: Vec<&str> = next
646 .iter()
647 .flatten()
648 .map(|held| held.mri.as_str())
649 .collect();
650 assert_eq!(
651 names,
652 vec!["8:orgid:p1", "8:orgid:p2", "8:orgid:p3", "8:orgid:p5"]
653 );
654 }
655
656 #[test]
657 fn people_who_left_free_their_slot() {
658 let held = vec![Some(assignment("a", 1)), Some(assignment("b", 2))];
659 let next = plan_receive(&held, &[assignment("b", 2)]);
660 assert_eq!(next, vec![None, Some(assignment("b", 2))]);
661 let slots = vec![
662 ReceiveSlot {
663 mid: "2".into(),
664 stream_id: 203,
665 },
666 ReceiveSlot {
667 mid: "3".into(),
668 stream_id: 204,
669 },
670 ];
671 let requests = requests_for(&held, &next, &slots, VideoQuality::Auto);
672 assert_eq!(
673 requests,
674 vec![SourceRequest {
675 mid: "2".into(),
676 stream_id: 203,
677 source: None,
678 screen: false,
679 detail: TileDetail::Stage,
680 quality: VideoQuality::Auto,
681 }]
682 );
683 }
684
685 #[test]
686 fn a_source_request_wraps_the_control_message_like_the_web_client() {
687 let request = SourceRequest {
688 mid: "3".into(),
689 stream_id: 204,
690 source: Some(302),
691 screen: false,
692 detail: TileDetail::Stage,
693 quality: VideoQuality::Auto,
694 };
695 let body = request.body(7);
696 let channel = &body["applyChannelParameters"]["multiChannelParameter"];
697 assert_eq!(channel["mids"], json!(["3"]));
698 let parameter: Value =
699 serde_json::from_str(channel["mediaParameter"].as_str().unwrap()).unwrap();
700 let info = &parameter["controlVideoStreaming"]["controlInfo"];
701 assert_eq!(parameter["controlVideoStreaming"]["sequenceNumber"], 7);
702 assert_eq!(info["sourceId"], 302);
703 assert_eq!(info["streamMsid"], 204);
704 assert_eq!(info["fmtParams"][0]["max-fs"], 8160);
705 assert_eq!(info["fmtParams"][0]["max-fps"], 3000);
706 assert_eq!(info["fmtParams"][0]["max-mbps"], 244_800);
707 assert_eq!(info["fmtParams"][0]["profile-level-id"], "64001f");
708 let cleared = SourceRequest {
709 source: None,
710 ..request.clone()
711 }
712 .body(8);
713 let parameter: Value = serde_json::from_str(
714 cleared["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"]
715 .as_str()
716 .unwrap(),
717 )
718 .unwrap();
719 assert_eq!(
720 parameter["controlVideoStreaming"]["controlInfo"]["sourceId"],
721 -1
722 );
723 let screen = SourceRequest {
724 screen: true,
725 ..request
726 }
727 .body(9);
728 let parameter: Value = serde_json::from_str(
729 screen["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"]
730 .as_str()
731 .unwrap(),
732 )
733 .unwrap();
734 assert_eq!(
735 parameter["controlVideoStreaming"]["controlInfo"]["fmtParams"][0]["max-fs"],
736 8160
737 );
738 }
739
740 fn want(name: &str, detail: TileDetail) -> VideoWant {
741 VideoWant {
742 mri: format!("8:orgid:{name}"),
743 detail,
744 }
745 }
746
747 fn roster_of(count: u32) -> Vec<(String, u32)> {
748 (1..=count)
749 .map(|index| (format!("8:orgid:p{index}"), index))
750 .collect()
751 }
752
753 #[test]
754 fn nine_slots_hold_nine_visible_people_and_the_tenth_waits() {
755 let wants: Vec<VideoWant> = (1..=10)
756 .map(|index| want(&format!("p{index}"), TileDetail::Small))
757 .collect();
758 let candidates = prioritize(roster_of(10), &[], Some(&wants));
759 let next = plan_receive(&vec![None; RECEIVE_SLOTS], &candidates);
760 assert_eq!(next.iter().flatten().count(), 9);
761 assert!(next.iter().flatten().all(|held| held.mri != "8:orgid:p10"));
762 }
763
764 #[test]
765 fn people_outside_the_visible_tiles_get_no_slot() {
766 let wants = vec![want("p2", TileDetail::Small), want("p4", TileDetail::Small)];
767 let candidates = prioritize(roster_of(5), &["8:orgid:p5".to_owned()], Some(&wants));
768 let mris: Vec<&str> = candidates
769 .iter()
770 .map(|assignment| assignment.mri.as_str())
771 .collect();
772 assert_eq!(mris, vec!["8:orgid:p2", "8:orgid:p4"]);
773 let held = vec![Some(assignment("p5", 5)), None, None];
774 let next = plan_receive(&held, &candidates);
775 assert_eq!(
776 next.iter()
777 .flatten()
778 .map(|held| held.mri.as_str())
779 .collect::<Vec<_>>(),
780 vec!["8:orgid:p2", "8:orgid:p4"]
781 );
782 }
783
784 #[test]
785 fn nobody_visible_means_no_subscription() {
786 assert!(prioritize(roster_of(3), &[], Some(&[])).is_empty());
787 }
788
789 #[test]
790 fn a_person_who_moves_to_the_stage_keeps_the_slot_and_gets_the_large_request() {
791 let small = Assignment {
792 detail: TileDetail::Small,
793 ..assignment("a", 1)
794 };
795 let held = vec![None, Some(small), None];
796 let wants = vec![want("a", TileDetail::Stage)];
797 let next = plan_receive(
798 &held,
799 &prioritize(vec![("8:orgid:a".to_owned(), 1)], &[], Some(&wants)),
800 );
801 assert_eq!(next, vec![None, Some(assignment("a", 1)), None]);
802 let slots: Vec<ReceiveSlot> = (0..3)
803 .map(|index| ReceiveSlot {
804 mid: format!("{}", index + 2),
805 stream_id: 203 + index,
806 })
807 .collect();
808 let requests = requests_for(&held, &next, &slots, VideoQuality::Auto);
809 assert_eq!(requests.len(), 1);
810 assert_eq!(requests[0].mid, "3");
811 assert_eq!(requests[0].detail, TileDetail::Stage);
812 }
813
814 #[test]
815 fn stage_and_small_tiles_ask_for_different_resolutions() {
816 let fmt_for = |detail| {
817 let request = SourceRequest {
818 mid: "2".into(),
819 stream_id: 203,
820 source: Some(1),
821 screen: false,
822 detail,
823 quality: VideoQuality::Auto,
824 };
825 let body = request.body(1);
826 let parameter: Value = serde_json::from_str(
827 body["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"]
828 .as_str()
829 .unwrap(),
830 )
831 .unwrap();
832 parameter["controlVideoStreaming"]["controlInfo"]["fmtParams"][0].clone()
833 };
834 assert_eq!(fmt_for(TileDetail::Stage)["max-fs"], 8160);
835 assert_eq!(fmt_for(TileDetail::Stage)["max-mbps"], 244_800);
836 assert_eq!(fmt_for(TileDetail::Small)["max-fs"], 920);
837 assert_eq!(fmt_for(TileDetail::Small)["max-mbps"], 27_600);
838 let locked = SourceRequest {
839 mid: "2".into(),
840 stream_id: 203,
841 source: Some(1),
842 screen: false,
843 detail: TileDetail::Stage,
844 quality: VideoQuality::P720,
845 }
846 .body(1);
847 let parameter: Value = serde_json::from_str(
848 locked["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"]
849 .as_str()
850 .unwrap(),
851 )
852 .unwrap();
853 assert_eq!(
854 parameter["controlVideoStreaming"]["controlInfo"]["fmtParams"][0]["max-fs"],
855 3600
856 );
857 }
858
859 #[test]
860 fn media_descriptions_tell_the_mixer_what_a_line_does() {
861 assert_eq!(
862 MediaDescription::camera(true).wire(),
863 json!({"mid": "1", "direction": "sendrecv", "label": "main-video"})
864 );
865 assert_eq!(
866 MediaDescription::camera(false).wire(),
867 json!({"mid": "1", "direction": "recvonly"})
868 );
869 assert_eq!(
870 MediaDescription::share(true).wire(),
871 json!({"mid": "11", "direction": "sendrecv", "label": "applicationsharing-video"})
872 );
873 assert_eq!(
874 MediaDescription::camera_line("7", true).wire(),
875 json!({"mid": "7", "direction": "sendrecv", "label": "main-video"})
876 );
877 }
878
879 #[test]
880 fn the_router_follows_assignments() {
881 let router = VideoRouter::default();
882 assert_eq!(router.key_for("2"), None);
883 router.set("2", Some(VideoKey::Person("8:orgid:a".into())));
884 assert_eq!(
885 router.key_for("2"),
886 Some(VideoKey::Person("8:orgid:a".into()))
887 );
888 router.set("2", None);
889 assert_eq!(router.key_for("2"), None);
890 }
891
892 #[test]
893 fn send_capabilities_name_the_camera_mid_and_the_largest_side() {
894 let body = send_capabilities_body(1280, 720, 4, VideoQuality::Auto);
895 let channel = &body["applyChannelParameters"]["multiChannelParameter"];
896 assert_eq!(channel["mids"], json!(["1"]));
897 let parameter: Value =
898 serde_json::from_str(channel["mediaParameter"].as_str().unwrap()).unwrap();
899 assert_eq!(
900 parameter,
901 json!({"maxVideoSendCapabilities": {
902 "max-width": 1280, "max-height": 1280, "max-fps": 30, "max-streams": 3, "max-layers": 3, "sequence-number": 4
903 }})
904 );
905 let small: Value = serde_json::from_str(
906 send_capabilities_body(480, 270, 1, VideoQuality::Auto)
907 ["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"]
908 .as_str()
909 .unwrap(),
910 )
911 .unwrap();
912 assert_eq!(small["maxVideoSendCapabilities"]["max-layers"], 2);
913 let clamped: Value =
914 serde_json::from_str(
915 send_capabilities_body(3840, 2160, 1, VideoQuality::P720)["applyChannelParameters"]
916 ["multiChannelParameter"]["mediaParameter"]
917 .as_str()
918 .unwrap(),
919 )
920 .unwrap();
921 assert_eq!(clamped["maxVideoSendCapabilities"]["max-width"], 1280);
922 assert_eq!(clamped["maxVideoSendCapabilities"]["max-height"], 1280);
923 }
924
925 #[test]
926 fn the_reporter_skips_a_repeated_size_and_counts_sequences() {
927 let mut reporter = SendCapabilityReporter::default();
928 assert!(reporter.body_for((1280, 720), VideoQuality::Auto).is_some());
929 assert!(reporter.body_for((1280, 720), VideoQuality::Auto).is_none());
930 let body = reporter.body_for((640, 480), VideoQuality::Auto).unwrap();
931 let parameter: Value = serde_json::from_str(
932 body["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"]
933 .as_str()
934 .unwrap(),
935 )
936 .unwrap();
937 assert_eq!(parameter["maxVideoSendCapabilities"]["sequence-number"], 2);
938 assert!(reporter.body_for((640, 480), VideoQuality::P720).is_some());
939 }
940}