BlueGit

ict rusty-teams

Files

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

video_layout.rs

video_layout.rs 29.6 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 // A folded `applicationsharing-video` line expands to several browser mids; only the last
313 // one carries `x-source-streamid`. Taking the first dropped the whole share slot.
314 let screen = streams
315 .iter()
316 .filter(|stream| stream.role == LineRole::ScreenShare)
317 .filter_map(slot)
318 .next_back();
319 SlotTable { people, screen }
320 }
321
322 pub fn is_empty(&self) -> bool {
323 self.people.is_empty() && self.screen.is_none()
324 }
325}
326
327#[derive(Debug, Clone, PartialEq, Eq)]
328pub struct Assignment {
329 pub mri: String,
330 pub source: u32,
331 pub detail: TileDetail,
332}
333
334impl Assignment {
335 fn same_source(&self, other: &Assignment) -> bool {
336 self.mri == other.mri && self.source == other.source
337 }
338}
339
340pub fn plan_receive(
341 current: &[Option<Assignment>],
342 candidates: &[Assignment],
343) -> Vec<Option<Assignment>> {
344 let wanted: Vec<&Assignment> = candidates.iter().take(current.len()).collect();
345 let mut next: Vec<Option<Assignment>> = current
346 .iter()
347 .map(|slot| {
348 let held = slot.as_ref()?;
349 wanted
350 .iter()
351 .find(|assignment| assignment.same_source(held))
352 .map(|assignment| (*assignment).clone())
353 })
354 .collect();
355 for assignment in wanted {
356 if next
357 .iter()
358 .flatten()
359 .any(|held| held.same_source(assignment))
360 {
361 continue;
362 }
363 if let Some(free) = next.iter_mut().find(|slot| slot.is_none()) {
364 *free = Some(assignment.clone());
365 }
366 }
367 next
368}
369
370pub fn prioritize(
371 candidates: Vec<(String, u32)>,
372 speaker_history: &[String],
373 wants: Option<&[VideoWant]>,
374) -> Vec<Assignment> {
375 if let Some(wants) = wants {
376 return wants
377 .iter()
378 .filter_map(|want| {
379 let (mri, source) = candidates.iter().find(|(mri, _)| *mri == want.mri)?;
380 Some(Assignment {
381 mri: mri.clone(),
382 source: *source,
383 detail: want.detail,
384 })
385 })
386 .collect();
387 }
388 let rank = |mri: &str| {
389 speaker_history
390 .iter()
391 .position(|speaker| speaker == mri)
392 .unwrap_or(usize::MAX)
393 };
394 let mut ordered: Vec<Assignment> = candidates
395 .into_iter()
396 .map(|(mri, source)| Assignment {
397 mri,
398 source,
399 detail: TileDetail::Stage,
400 })
401 .collect();
402 ordered.sort_by_key(|assignment| rank(&assignment.mri));
403 ordered
404}
405
406#[derive(Debug, Clone, PartialEq, Eq)]
407pub struct SourceRequest {
408 pub mid: String,
409 pub stream_id: u32,
410 pub source: Option<u32>,
411 pub screen: bool,
412 pub detail: TileDetail,
413 pub quality: VideoQuality,
414}
415
416pub fn requests_for(
417 current: &[Option<Assignment>],
418 next: &[Option<Assignment>],
419 slots: &[ReceiveSlot],
420 quality: VideoQuality,
421) -> Vec<SourceRequest> {
422 slots
423 .iter()
424 .zip(current.iter().zip(next))
425 .filter(|(_, (before, after))| before != after)
426 .map(|(slot, (_, after))| SourceRequest {
427 mid: slot.mid.clone(),
428 stream_id: slot.stream_id,
429 source: after.as_ref().map(|assignment| assignment.source),
430 screen: false,
431 detail: after
432 .as_ref()
433 .map(|assignment| assignment.detail)
434 .unwrap_or_default(),
435 quality,
436 })
437 .collect()
438}
439
440impl SourceRequest {
441 /// Body of the `applyChannelParameters` link, the signaling twin of the data-channel `sr` message.
442 pub fn body(&self, sequence_number: u64) -> Value {
443 let limits = if self.screen {
444 SCREEN_REQUEST
445 } else {
446 self.detail.limits(self.quality)
447 };
448 let control = json!({
449 "controlVideoStreaming": {
450 "sequenceNumber": sequence_number,
451 "controlInfo": {
452 "sourceId": self.source.map_or(NO_SOURCE, i64::from),
453 "streamMsid": self.stream_id,
454 "fmtParams": [{
455 "max-fs": limits.max_fs,
456 "max-mbps": limits.max_mbps,
457 "max-fps": limits.max_fps,
458 "profile-level-id": SUBSCRIBE_PROFILE,
459 }],
460 },
461 },
462 });
463 json!({
464 "applyChannelParameters": {
465 "multiChannelParameter": {
466 "mids": [self.mid],
467 "mediaParameter": control.to_string(),
468 },
469 },
470 })
471 }
472}
473
474pub fn send_capabilities_body(
475 width: u32,
476 height: u32,
477 sequence_number: u64,
478 quality: VideoQuality,
479) -> Value {
480 send_capabilities_body_for(CAMERA_MID, width, height, sequence_number, quality)
481}
482
483pub fn send_capabilities_body_for(
484 camera_mid: &str,
485 width: u32,
486 height: u32,
487 sequence_number: u64,
488 quality: VideoQuality,
489) -> Value {
490 let ceiling = quality.capture_height().max(quality.capture_width());
491 let width = width.min(ceiling);
492 let height = height.min(ceiling);
493 let largest_side = width.max(height);
494 let layers = if capture_macroblocks(width, height) < THREE_LAYER_MIN_FS {
495 2
496 } else {
497 SIMULCAST_RIDS.len()
498 };
499 let capabilities = json!({
500 "maxVideoSendCapabilities": {
501 "max-width": largest_side,
502 "max-height": largest_side,
503 "max-fps": SEND_CAPABILITY_FPS,
504 "max-streams": SIMULCAST_RIDS.len(),
505 "max-layers": layers,
506 "sequence-number": sequence_number,
507 },
508 });
509 json!({
510 "applyChannelParameters": {
511 "multiChannelParameter": {
512 "mids": [camera_mid],
513 "mediaParameter": capabilities.to_string(),
514 },
515 },
516 })
517}
518
519/// Builds a send-capability body only when the camera size differs from the last one reported.
520#[derive(Debug, Default)]
521pub struct SendCapabilityReporter {
522 last_size: Option<(u32, u32)>,
523 last_quality: Option<VideoQuality>,
524 sequence_number: u64,
525}
526
527impl SendCapabilityReporter {
528 pub fn body_for(&mut self, size: (u32, u32), quality: VideoQuality) -> Option<Value> {
529 self.body_for_mid(CAMERA_MID, size, quality)
530 }
531
532 pub fn body_for_mid(
533 &mut self,
534 camera_mid: &str,
535 size: (u32, u32),
536 quality: VideoQuality,
537 ) -> Option<Value> {
538 if self.last_size == Some(size) && self.last_quality == Some(quality) {
539 return None;
540 }
541 self.last_size.replace(size);
542 self.last_quality.replace(quality);
543 self.sequence_number += 1;
544 Some(send_capabilities_body_for(
545 camera_mid,
546 size.0,
547 size.1,
548 self.sequence_number,
549 quality,
550 ))
551 }
552}
553
554#[derive(Clone, Default)]
555pub struct VideoRouter {
556 keys: Arc<Mutex<HashMap<String, VideoKey>>>,
557}
558
559impl VideoRouter {
560 pub fn set(&self, mid: &str, key: Option<VideoKey>) {
561 let mut keys = self.keys.lock().expect("router lock");
562 match key {
563 Some(key) => keys.insert(mid.to_owned(), key),
564 None => keys.remove(mid),
565 };
566 }
567
568 pub fn key_for(&self, mid: &str) -> Option<VideoKey> {
569 self.keys.lock().expect("router lock").get(mid).cloned()
570 }
571}
572
573#[cfg(test)]
574mod tests {
575 use super::*;
576
577 fn assignment(name: &str, source: u32) -> Assignment {
578 Assignment {
579 mri: format!("8:orgid:{name}"),
580 source,
581 detail: TileDetail::Stage,
582 }
583 }
584
585 fn stream(mid: &str, role: LineRole, id: Option<u32>) -> StreamLine {
586 StreamLine {
587 mid: mid.into(),
588 browser_mid: mid.into(),
589 role,
590 source_stream_id: id,
591 }
592 }
593
594 #[test]
595 fn slots_are_the_main_video_lines_after_the_camera_line() {
596 let streams = vec![
597 stream("0", LineRole::MainAudio, Some(201)),
598 stream("1", LineRole::MainVideo, Some(202)),
599 stream("2", LineRole::MainVideo, Some(203)),
600 stream("3", LineRole::MainVideo, Some(204)),
601 stream("4", LineRole::MainVideo, None),
602 stream("5", LineRole::MainVideo, Some(206)),
603 stream("11", LineRole::ScreenShare, Some(207)),
604 ];
605 let table = SlotTable::from_streams(&streams);
606 let mids: Vec<&str> = table.people.iter().map(|slot| slot.mid.as_str()).collect();
607 assert_eq!(mids, vec!["2", "3", "5"]);
608 assert_eq!(
609 table.screen,
610 Some(ReceiveSlot {
611 mid: "11".into(),
612 stream_id: 207
613 })
614 );
615 }
616
617 #[test]
618 fn a_folded_share_line_keeps_its_receive_slot() {
619 let streams = vec![
620 stream("1", LineRole::MainVideo, Some(202)),
621 stream("10", LineRole::ScreenShare, None),
622 stream("11", LineRole::ScreenShare, Some(207)),
623 ];
624 let table = SlotTable::from_streams(&streams);
625 assert_eq!(
626 table.screen,
627 Some(ReceiveSlot {
628 mid: "11".into(),
629 stream_id: 207
630 })
631 );
632 }
633
634 #[test]
635 fn nobody_is_dropped_while_they_are_still_wanted() {
636 let held = vec![
637 Some(assignment("a", 1)),
638 Some(assignment("b", 2)),
639 None,
640 None,
641 ];
642 let candidates = vec![assignment("c", 3), assignment("a", 1), assignment("b", 2)];
643 let next = plan_receive(&held, &candidates);
644 assert_eq!(next[0], Some(assignment("a", 1)));
645 assert_eq!(next[1], Some(assignment("b", 2)));
646 assert_eq!(next[2], Some(assignment("c", 3)));
647 assert_eq!(next[3], None);
648 }
649
650 #[test]
651 fn a_new_speaker_replaces_the_least_recent_person() {
652 let held: Vec<Option<Assignment>> = (1..=4)
653 .map(|index| Some(assignment(&format!("p{index}"), index)))
654 .collect();
655 let history = vec![
656 "8:orgid:p5".to_owned(),
657 "8:orgid:p1".to_owned(),
658 "8:orgid:p2".to_owned(),
659 "8:orgid:p3".to_owned(),
660 ];
661 let roster = (1..=5)
662 .map(|index| (format!("8:orgid:p{index}"), index))
663 .collect();
664 let next = plan_receive(&held, &prioritize(roster, &history, None));
665 let names: Vec<&str> = next
666 .iter()
667 .flatten()
668 .map(|held| held.mri.as_str())
669 .collect();
670 assert_eq!(
671 names,
672 vec!["8:orgid:p1", "8:orgid:p2", "8:orgid:p3", "8:orgid:p5"]
673 );
674 }
675
676 #[test]
677 fn people_who_left_free_their_slot() {
678 let held = vec![Some(assignment("a", 1)), Some(assignment("b", 2))];
679 let next = plan_receive(&held, &[assignment("b", 2)]);
680 assert_eq!(next, vec![None, Some(assignment("b", 2))]);
681 let slots = vec![
682 ReceiveSlot {
683 mid: "2".into(),
684 stream_id: 203,
685 },
686 ReceiveSlot {
687 mid: "3".into(),
688 stream_id: 204,
689 },
690 ];
691 let requests = requests_for(&held, &next, &slots, VideoQuality::Auto);
692 assert_eq!(
693 requests,
694 vec![SourceRequest {
695 mid: "2".into(),
696 stream_id: 203,
697 source: None,
698 screen: false,
699 detail: TileDetail::Stage,
700 quality: VideoQuality::Auto,
701 }]
702 );
703 }
704
705 #[test]
706 fn a_source_request_wraps_the_control_message_like_the_web_client() {
707 let request = SourceRequest {
708 mid: "3".into(),
709 stream_id: 204,
710 source: Some(302),
711 screen: false,
712 detail: TileDetail::Stage,
713 quality: VideoQuality::Auto,
714 };
715 let body = request.body(7);
716 let channel = &body["applyChannelParameters"]["multiChannelParameter"];
717 assert_eq!(channel["mids"], json!(["3"]));
718 let parameter: Value =
719 serde_json::from_str(channel["mediaParameter"].as_str().unwrap()).unwrap();
720 let info = &parameter["controlVideoStreaming"]["controlInfo"];
721 assert_eq!(parameter["controlVideoStreaming"]["sequenceNumber"], 7);
722 assert_eq!(info["sourceId"], 302);
723 assert_eq!(info["streamMsid"], 204);
724 assert_eq!(info["fmtParams"][0]["max-fs"], 8160);
725 assert_eq!(info["fmtParams"][0]["max-fps"], 3000);
726 assert_eq!(info["fmtParams"][0]["max-mbps"], 244_800);
727 assert_eq!(info["fmtParams"][0]["profile-level-id"], "64001f");
728 let cleared = SourceRequest {
729 source: None,
730 ..request.clone()
731 }
732 .body(8);
733 let parameter: Value = serde_json::from_str(
734 cleared["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"]
735 .as_str()
736 .unwrap(),
737 )
738 .unwrap();
739 assert_eq!(
740 parameter["controlVideoStreaming"]["controlInfo"]["sourceId"],
741 -1
742 );
743 let screen = SourceRequest {
744 screen: true,
745 ..request
746 }
747 .body(9);
748 let parameter: Value = serde_json::from_str(
749 screen["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"]
750 .as_str()
751 .unwrap(),
752 )
753 .unwrap();
754 assert_eq!(
755 parameter["controlVideoStreaming"]["controlInfo"]["fmtParams"][0]["max-fs"],
756 8160
757 );
758 }
759
760 fn want(name: &str, detail: TileDetail) -> VideoWant {
761 VideoWant {
762 mri: format!("8:orgid:{name}"),
763 detail,
764 }
765 }
766
767 fn roster_of(count: u32) -> Vec<(String, u32)> {
768 (1..=count)
769 .map(|index| (format!("8:orgid:p{index}"), index))
770 .collect()
771 }
772
773 #[test]
774 fn nine_slots_hold_nine_visible_people_and_the_tenth_waits() {
775 let wants: Vec<VideoWant> = (1..=10)
776 .map(|index| want(&format!("p{index}"), TileDetail::Small))
777 .collect();
778 let candidates = prioritize(roster_of(10), &[], Some(&wants));
779 let next = plan_receive(&vec![None; RECEIVE_SLOTS], &candidates);
780 assert_eq!(next.iter().flatten().count(), 9);
781 assert!(next.iter().flatten().all(|held| held.mri != "8:orgid:p10"));
782 }
783
784 #[test]
785 fn people_outside_the_visible_tiles_get_no_slot() {
786 let wants = vec![want("p2", TileDetail::Small), want("p4", TileDetail::Small)];
787 let candidates = prioritize(roster_of(5), &["8:orgid:p5".to_owned()], Some(&wants));
788 let mris: Vec<&str> = candidates
789 .iter()
790 .map(|assignment| assignment.mri.as_str())
791 .collect();
792 assert_eq!(mris, vec!["8:orgid:p2", "8:orgid:p4"]);
793 let held = vec![Some(assignment("p5", 5)), None, None];
794 let next = plan_receive(&held, &candidates);
795 assert_eq!(
796 next.iter()
797 .flatten()
798 .map(|held| held.mri.as_str())
799 .collect::<Vec<_>>(),
800 vec!["8:orgid:p2", "8:orgid:p4"]
801 );
802 }
803
804 #[test]
805 fn nobody_visible_means_no_subscription() {
806 assert!(prioritize(roster_of(3), &[], Some(&[])).is_empty());
807 }
808
809 #[test]
810 fn a_person_who_moves_to_the_stage_keeps_the_slot_and_gets_the_large_request() {
811 let small = Assignment {
812 detail: TileDetail::Small,
813 ..assignment("a", 1)
814 };
815 let held = vec![None, Some(small), None];
816 let wants = vec![want("a", TileDetail::Stage)];
817 let next = plan_receive(
818 &held,
819 &prioritize(vec![("8:orgid:a".to_owned(), 1)], &[], Some(&wants)),
820 );
821 assert_eq!(next, vec![None, Some(assignment("a", 1)), None]);
822 let slots: Vec<ReceiveSlot> = (0..3)
823 .map(|index| ReceiveSlot {
824 mid: format!("{}", index + 2),
825 stream_id: 203 + index,
826 })
827 .collect();
828 let requests = requests_for(&held, &next, &slots, VideoQuality::Auto);
829 assert_eq!(requests.len(), 1);
830 assert_eq!(requests[0].mid, "3");
831 assert_eq!(requests[0].detail, TileDetail::Stage);
832 }
833
834 #[test]
835 fn stage_and_small_tiles_ask_for_different_resolutions() {
836 let fmt_for = |detail| {
837 let request = SourceRequest {
838 mid: "2".into(),
839 stream_id: 203,
840 source: Some(1),
841 screen: false,
842 detail,
843 quality: VideoQuality::Auto,
844 };
845 let body = request.body(1);
846 let parameter: Value = serde_json::from_str(
847 body["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"]
848 .as_str()
849 .unwrap(),
850 )
851 .unwrap();
852 parameter["controlVideoStreaming"]["controlInfo"]["fmtParams"][0].clone()
853 };
854 assert_eq!(fmt_for(TileDetail::Stage)["max-fs"], 8160);
855 assert_eq!(fmt_for(TileDetail::Stage)["max-mbps"], 244_800);
856 assert_eq!(fmt_for(TileDetail::Small)["max-fs"], 920);
857 assert_eq!(fmt_for(TileDetail::Small)["max-mbps"], 27_600);
858 let locked = SourceRequest {
859 mid: "2".into(),
860 stream_id: 203,
861 source: Some(1),
862 screen: false,
863 detail: TileDetail::Stage,
864 quality: VideoQuality::P720,
865 }
866 .body(1);
867 let parameter: Value = serde_json::from_str(
868 locked["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"]
869 .as_str()
870 .unwrap(),
871 )
872 .unwrap();
873 assert_eq!(
874 parameter["controlVideoStreaming"]["controlInfo"]["fmtParams"][0]["max-fs"],
875 3600
876 );
877 }
878
879 #[test]
880 fn media_descriptions_tell_the_mixer_what_a_line_does() {
881 assert_eq!(
882 MediaDescription::camera(true).wire(),
883 json!({"mid": "1", "direction": "sendrecv", "label": "main-video"})
884 );
885 assert_eq!(
886 MediaDescription::camera(false).wire(),
887 json!({"mid": "1", "direction": "recvonly"})
888 );
889 assert_eq!(
890 MediaDescription::share(true).wire(),
891 json!({"mid": "11", "direction": "sendrecv", "label": "applicationsharing-video"})
892 );
893 assert_eq!(
894 MediaDescription::camera_line("7", true).wire(),
895 json!({"mid": "7", "direction": "sendrecv", "label": "main-video"})
896 );
897 }
898
899 #[test]
900 fn the_router_follows_assignments() {
901 let router = VideoRouter::default();
902 assert_eq!(router.key_for("2"), None);
903 router.set("2", Some(VideoKey::Person("8:orgid:a".into())));
904 assert_eq!(
905 router.key_for("2"),
906 Some(VideoKey::Person("8:orgid:a".into()))
907 );
908 router.set("2", None);
909 assert_eq!(router.key_for("2"), None);
910 }
911
912 #[test]
913 fn send_capabilities_name_the_camera_mid_and_the_largest_side() {
914 let body = send_capabilities_body(1280, 720, 4, VideoQuality::Auto);
915 let channel = &body["applyChannelParameters"]["multiChannelParameter"];
916 assert_eq!(channel["mids"], json!(["1"]));
917 let parameter: Value =
918 serde_json::from_str(channel["mediaParameter"].as_str().unwrap()).unwrap();
919 assert_eq!(
920 parameter,
921 json!({"maxVideoSendCapabilities": {
922 "max-width": 1280, "max-height": 1280, "max-fps": 30, "max-streams": 3, "max-layers": 3, "sequence-number": 4
923 }})
924 );
925 let small: Value = serde_json::from_str(
926 send_capabilities_body(480, 270, 1, VideoQuality::Auto)["applyChannelParameters"]
927 ["multiChannelParameter"]["mediaParameter"]
928 .as_str()
929 .unwrap(),
930 )
931 .unwrap();
932 assert_eq!(small["maxVideoSendCapabilities"]["max-layers"], 2);
933 let clamped: Value =
934 serde_json::from_str(
935 send_capabilities_body(3840, 2160, 1, VideoQuality::P720)["applyChannelParameters"]
936 ["multiChannelParameter"]["mediaParameter"]
937 .as_str()
938 .unwrap(),
939 )
940 .unwrap();
941 assert_eq!(clamped["maxVideoSendCapabilities"]["max-width"], 1280);
942 assert_eq!(clamped["maxVideoSendCapabilities"]["max-height"], 1280);
943 }
944
945 #[test]
946 fn the_reporter_skips_a_repeated_size_and_counts_sequences() {
947 let mut reporter = SendCapabilityReporter::default();
948 assert!(reporter.body_for((1280, 720), VideoQuality::Auto).is_some());
949 assert!(reporter.body_for((1280, 720), VideoQuality::Auto).is_none());
950 let body = reporter.body_for((640, 480), VideoQuality::Auto).unwrap();
951 let parameter: Value = serde_json::from_str(
952 body["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"]
953 .as_str()
954 .unwrap(),
955 )
956 .unwrap();
957 assert_eq!(parameter["maxVideoSendCapabilities"]["sequence-number"], 2);
958 assert!(reporter.body_for((640, 480), VideoQuality::P720).is_some());
959 }
960}